线性表顺序储存的建立,查找,插入,删除

 1 typedef struct LNode *List
 2 
 3 struct Lnode {
 4 
 5     ElementType Data[MAXSIZE];
 6 
 7     int Last;  //线性表最后一个元素
 8 
 9 };
10 
11 struct LNode L;
12 
13 List PtrL;

访问下标为i的元素:L.Data[i]或者PtrL->Data[i]

线性表的长度:L.Last+1或者PtrL->Last+1

1.初始化(建立空的顺序表)

1 List MakeEmpty(){
2     List PtrL;
3     PtrL = (List)malloc(sizeof(struct LNode));
4     PtrL->Last = -1;  //Last为0表示有一个元素放在第一个位置
5     return PtrL;  //把结构的指针返回
6 }    //创建并返回一个空的线性表;

2.查找(find)

1 int Find( List L, ElementType X ){
2     int i = 0;
3     while (i <= PtrL->Last && PtrL->Data[i] != X){
4         i++;
5     }
6     if (i >PtrL->Last)    return -1;
7     else return i;    //找到后返回储存位置
8 }

3.插入(在第i个位置插入值为X的元素)

先移动,再插入。

从后往前挪动。

void Insert( List L, ElementType X, int i){ 
    int j;
    if (PtrL->Last == MAXSIZE-1)
        printf("表满");
        return 0;
    if (i<1 || PtrL->Last+2)
        printf("位置不合法");
        teturn 0;
    for (j=PtrL->Last; j>=i-1; j--)
        PtrL->Data[j+1] = PtrL->Data[j];
    PtrL->Data[i-1] = X;    //新元素插入
    PtrL->Last++;    //Last仍指向最后元素
    reutrn 0;
}

4.删除(删除表的第i个位置上的元素)

把i之后的元素往前挪

void Delete( List L, int i ){
    int j;
    if (i<1 || i>PtrL->Last+1)
        printf("不存在第%d个元素", i);
        return 0;
    for (j=i; j<=PtrL->Last; j++)
        PtrL->Data[j-1] = PtrL->Data[j];
    PtrL->Last--;    //Last仍指向最后元素
    return 0;
}

 

原文地址:https://www.cnblogs.com/zhengxin909/p/12451592.html