数据结构复盘——线性表的链式存储

    科技2022-08-17  111

    #include <stdio.h> #include <stdlib.h> #define ERROR NULL typedef struct LNode *PtrToLNode; //定义 struct LNode{ int data; PtrToLNode next; }; typedef PtrToLNode Position; typedef PtrToLNode List; //初始化 List MakeEmpty(){ List L; L=(List)malloc(sizeof(struct LNode)); if(!L) exit(-1); L->next=NULL; return L; } //插入 List Insert(List L ,int x,int i){ Position temp,p=L; int count =0; while(p && count<i-1){ p = p->next; count++; } if(p==NULL||count!=i-1){ printf("插入位置参数错误\n"); return ERROR; } else{ temp = (Position)malloc(sizeof(struct LNode)); temp->data=x; temp->next=p->next; p->next=temp; return L; } } //删除 bool Delete(List L,int i){ Position temp,pre=L; int count=0; while(pre && count<i-1){ pre=pre->next; count++; } if(pre==NULL || count!=i-1 || pre->next==NULL){ printf("删除的位置不合法!"); return false; }else{ temp=pre->next; pre->next=temp->next; free(temp); return true; } } //查找 int Find(List L,int i){ Position p=L->next; int count=1; while(p && count<i){ p=p->next; count++; } if(p && count==i){ return printf("查找的元素为:%d",p->data); }else{ return ERROR; } } //求表长 int Length(List L){ Position p=L->next; int count=0; while(p){ p=p->next; count++; } return count; } //输出 void output(List L) { List p = L->next; while (p) { printf("%d ", p->data); p = p->next; } } //主函数 void main(){ List L=MakeEmpty(); int num,x,del,find; printf("请输入数据个数:"); scanf("%d",&num); for(int i=1;i<=num;i++){ scanf("%d",&x); Insert(L,x,i); } output(L); printf("\n"); printf("请输入查找的下标:"); scanf("%d",&find); Find(L,find); printf("\n"); printf("请输入要删除的位置:"); scanf("%d",&del); Delete(L,del); output(L); printf("\n"); int l=Length(L); printf("数组长度为:%d",l); printf("\n"); }
    Processed: 0.009, SQL: 9