首页 > 其他分享 >线性表_顺序表简单实现

线性表_顺序表简单实现

时间:2022-11-02 22:25:01浏览次数:87  
标签:顺序 return 线性表 Position printf List 简单 Last Data

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

#define ElementType int
#define MAXSIZE 100
#define ERROR -1

typedef int Position;
typedef struct LNode *List;
struct LNode{
    ElementType Data[MAXSIZE];
    Position Last;
};

List MakeEmpty(void){
    List L;
    
    L = (List)malloc(sizeof(struct LNode));
    L->Last = -1;
    
    return L;
}

Position Find(List L, ElementType X){
    Position i = 0;
    
    while (i <= L->Last && L->Data[i] != X) {
        i++;
    }
    if(i > L->Last) return ERROR;
    else return i;
}

bool Insert(List L, ElementType X, Position P){
    Position i;
    
    if(L->Last == MAXSIZE - 1){
        printf("表满");
        return false;
    }
    
    if(P < 0 || P > L->Last + 1){
        printf("位置不合法");
        return false;
    }
    for (i = L->Last; i >= P; i--) {
        L->Data[i+1] = L->Data[i];
    }
    L->Data[P] = X;
    L->Last++;
    return true;
}

bool Delete(List L, Position P){
    Position i;
    
    if(P < 0 || P > L->Last){
        printf("位置%d不存在元素",P);
        return false;
    }
    
    for (i = P+1; i <= L->Last; i++) {
        L->Data[i-1] = L->Data[i];
    }
    L->Last--;
    return true;
}

void VisitList(List L){
    Position i;
    for (i = 0; i <= L->Last; ++i) {
        printf("%d ",L->Data[i]);
    }
    printf("\n");
}

int main(){
    List L = MakeEmpty();
    Insert(L, 0, 0);
    Insert(L, 1, 1);
    Insert(L, 2, 2);
    VisitList(L);
    int i = Find(L, 1);
    printf("1在第%d个位置\n",i);
    Delete(L, 1);
    VisitList(L);
    return 0;
}

 

标签:顺序,return,线性表,Position,printf,List,简单,Last,Data
From: https://www.cnblogs.com/xinrenbool/p/16852745.html

相关文章