《数据结构C语言版 单链表源代码.docx》由会员分享,可在线阅读,更多相关《数据结构C语言版 单链表源代码.docx(12页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、/*单链表的各种操作*/# include include (malloc。h)# define null 0typedef int ElemType;/* 字符型数据*/struct LNode(ElemType data;struct LNode next;);void setnull(struct LNode * * p);int length (struct LNode * *p);ElemType get (struct LNode * * p,int i);void insert(struct LNode *p, ElemType x , int i);void dele (str
2、uct LNode *p , int i);void display (struct LNode * * p);int locate(struct LNode * * p,ElemType x);void main()(struct LNode *head , *q; /*定义静态变量*/int select, x1 , x2, x3,x4;int i,n;printf ( %d”,q- data);)printfC5;int m, g;chare, y;setnull (&head);/*建设链表并设置为空表*/printf (请输入数据长度:”);scant ( %;for (i=1;i=
3、n;i+)j iprintf(将数据插入到单链表中scanfC,%d, &y);insert (&head , y, i);/*插入数据到链表*/display (&head); /*显示链表所有数据*/求长度length ();取结点get();printf ( 求值查找;删除结点delete。 );printf ( select 0 退出”);printf ();% , & select);while(select! =0) switch (select)easel:x1=length(&head);printf(输出单链表的长度! ”,x1);display(&head);break;c
4、ase 2:I:printf(”请输入要取得结点:”); scant ( %d”,&m)x2=get (&head,m); printf(,%d,x2);display (&head); break;case 3:(请输入要查找的数据:”);scant (d,&e);x3=locate (&head,e);printfC,%d,9, x3); display(&head); break;case 4:printf(请输入要删除的结点:”);scant (, &g);dele (&head, g);display (&head); break;printf(, select 1 求长度 leng
5、th () ”); printf( select 2 取结点 get ();printf (v select 3 求值查找 locate 0 );printf ( select 4 删除结点 delete()printf(v select 0 退出”);printf (input your select:scanf( % d,9,&select);void setnull (struct LNode * * p)(*p=null;int length (struct LNode *火 p)int n=0;struct LNode *q=*p;while (q! =null)(n+;q=q-ne
6、xt;)return (n);)ElemType get (struct LNode * * p,int i) (int j=1;struct LNode *q=*p;while (j next;j+;if (q!=null)return (qdata);elseprintf (位置参数不正确!return 0; int locate(struct LNode * 火 p,ElemType x)(int n=0;struct LNode *q=*p;while (q!=null&q-data! =x)(q=qnext;n+;)if(q=null)return(-1);elsereturn(n+
7、1);)void insert (struct LNode *p , ElemType x , int i)(struct LNode *s,*q;s=(struct LNode *)malloc(sizeof (struct LNode);sdata=x;q=*p;if(i=1)(s) next=q;*P=s;)else(while(jnext;j+;)if(j=i-1)(snext=q-next;q一next=s;elseprintf(位置参数不正确! ” );void dele(struct LNode * *p,int i)int j=1 ;struct LNode * q=*p, *t;if(i=1)(t=q;*p=q-) next;else(while (jnext! =null&j=i-1)(t=qnext;elseprintf( 位置参数不正确!if(t!=null) free (t);void display (struct LNode *p)(struct LNode *q;q=p;printf (单链表显示:”);if (q=null)printf (链表为空!);else if (q-next=null) n”, q-data);else(while (q-next! =null)printfC%d”,qdata);q=qnext;
限制150内