线性表的实现

在这里插入图片描述

数组实现线性表
typedef int Position;
typedef struct LNode *List;
struct LNode{
    ElementType Data[MAXSIZE];
    Position Last;
};
typedef int bool;
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define MAXSIZE 1000
/*初始化*/
List  makeEmpty(){
    List L;
    L = (List)malloc(sizeof(struct LNode));
    L->Last = -1;
    return L;
}
/*查找第k个元素*/
ElementType FindKth(int k,List L){
    if((k+1) > L->Last || k<1){
        return NULL;
    }
    return Data[k-1];
}
/*再线性表中查找x第一次出现的位置*/

int Find(ELementType x,List L){
    for(int i=0;i<=L->Last;i++){
        if(L->Data[i]==x){
            return i;
        }
    }
    return ERROR;
}
/*在位序列i前插入一个新元素x*/
bool Insert(ElementType X,int i,List L){
    /*表满!*/
    if(L->Last==MAXSIZE-1){
        return FALSE;
    }
    /*位置有误!*/
    if(i < 0 || i > L->Last+1 ){
        return FALSE;
    }
    for(int j=L->Last;j>=i-1;j--){
        L->Data[j+1] =L->Data[j];
    }

    L->Data[i-1] = x;
    L->Last++;
    return TRUE;


}
/*删除指定位序i的元素*/
bool Delete(int i,List L){
    if(i<0 || i>L->Last || L->Last < 0){
        return FALSE;
    }
    for(int j=i-1;j<L->Last;j++){
        L->Data[j] = L->Data[j+1];
    }
    L->Last--;
    return TRUE;

}
/*返回线性表L的长度n*/
int Length(List L){
    return L->Last+1;
}

链表实现线性表
typedef struct LNode *PtrToLNode;
struct LNode {
    ElementType Data;
    PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
typedef int bool;
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define MAXSIZE 1000
/*初始化*/
List  makeEmpty(){
    List L;
    L = (List)malloc(sizeof(struct LNode));
    L->Next = NULL;
    return L;
}
/*查找第k个元素*/
ElementType FindKth(int k,List L){
    Position p=L;
    int i=0;
    while(p && i <= k-1  ){
        p=p->Next;
        i++;
    }
    return p->Data;
}
/*再线性表中查找x第一次出现的位置*/

Position Find(ELementType x,List L){
    Position p=L;
    while(p && p -> Data != x)
        p = p -> Next;
    return p;
}
/*在位序列i前插入一个新元素x*/
bool Insert(ElementType X,Position p,List L){
    Position pre,temp;

    for(pre=L;pre&&pre->Data !=p;pre=pre->Next);
    if(pre==NULL){
        return FALSE;
    }else{
        temp = (Position)malloc(sizeof(struct LNode));
        temp->Next = pre->Next;
        temp ->Data = X;
        pre->Next = temp;
        return TRUE;
    }

}
/*删除指定位序i的元素*/
bool Delete(Position p,List L){
    Position pre,temp;
    for(pre=L;pre&&pre->Data !=p;pre=pre->Next);
    if(pre == NULL || p==NULL){
        return FALSE;
    }else{
        pre->Next = pre->Next->Next;
        free(p);
        return TRUE;
    }
}
/*返回线性表L的长度n*/
int Length(List L){
    int i=0;
    for(L){
        i++;
        L=L->Next;
    }
    return i;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值