《实验十链表操作》由会员分享,可在线阅读,更多相关《实验十链表操作(4页珍藏版)》请在金锄头文库上搜索。
1、实验十 链表操作实验目的 掌握链表的定义和使用方法,能熟练进行链表的各种操作。实验内容 定义一学生链表,完成建立链表、打印链表、插入链表和删除链表操作。实验步骤(1)分别定义四个函数create( ),print( ), insert( ),del( )。(2)在主函数中调用上述函数,测试各函数的功能。源程序:#include#includestruct studentint no;struct student *next;/建立链表struct student *create()struct student *head,*p1,*p2;head=NULL;p1=p2=(struct stud
2、ent *)malloc(sizeof (struct student);scanf(%d,&p1-no);while(p1-no!=0)if (head=NULL) head=p1;else p2-next=p1;p2=p1;p1=(struct student *)malloc(sizeof (struct student);scanf(%d,&p1-no);p2-next=NULL;return head;/打印链表void print(struct student *head)struct student *p;p=head;while(p!=NULL) printf(%5d,p-no
3、); p=p-next; printf(n);/删除链表struct student *del(struct student *head,int num) struct student *p1,*p2;if (head=NULL) printf(NULLn);elsep1=head;while(p1-no!=num&p1-next!=NULL)p2=p1;p1=p1-next;if (p1-no=num) if (p1=head) head=head-next; else p2-next=p1-next; free(p1); printf(delete success!n); else pri
4、ntf(not foundn);/这一块是对应原来的循环条件return head;/用递归反向输出链表void output(struct student *head)if (head-next!=NULL) output(head-next); printf(%5d, head-no); /用递归(recursion)正向输出链表void output1(struct student *head)if (head!=NULL) printf(%5d, head-no); output1(head-next); main()struct student *head,*head1;int num;head=create();output1(head);/print(head);printf(n);printf(n);scanf(%d,&num);head=del(head,num);print(head);