《用C++创建、输出链表,查找、插入、删除结点》由会员分享,可在线阅读,更多相关《用C++创建、输出链表,查找、插入、删除结点(3页珍藏版)》请在金锄头文库上搜索。
1、#include struct node /定义链表的结点int data; /要存在结点的整数node *next; /指向下一个结点的指针;node *creatlist(int); /创建链表函数void outputlist(node *);node *findlist(int n,node *head); /查找结点函数node *insertlist(int n,node *head); /插入结点函数node *deletlist(int n,node *head); /删除结点函数void main() /主函数int n,find,insert,delet;node *lis
2、tinsert=NULL;node *listhead=NULL;node *listdelete=NULL;coutn;listhead=creatlist(n); /调用创建链表函数;outputlist(listhead); /输出链表;coutfind;findlist(find,listhead);coutinsert;listinsert=insertlist(insert,listhead);outputlist(listinsert);coutdelet;listdelete=deletlist(delet,listhead);outputlist(listdelete);no
3、de *creatlist(int n) /创建链表函数node *temp=NULL,*head=NULL,*tail=NULL;int num;coutnum;head=new node; /分配动态存储空间;if(head=NULL) coutdata=num; head-next=NULL;tail=head;for(int i=0;inum;temp=new node;if(temp=NULL) coutdata=num; temp-next=NULL;tail-next=temp;tail=temp;return head;void outputlist(node *head)no
4、de *curnode=head; /定义一个动态查找指针,指向头结点;while(curnode)coutdata;if(curnode-next) cout;curnode=curnode-next;coutdata=n)coutnext;coutdatanext;newnode=new node;if(newnode=NULL) coutdata=n;if(prenode=NULL) /在链表表头插入结点;newnode-next=curnode; return newnode;else prenode-next=newnode; newnode-next=curnode; return head; /在链表中插入结点node *deletlist(int n,node*head) /删除结点函数node *prenode=NULL;node *curnode=head;while(curnode!=NULL&curnode-data!=n)prenode=curnode; curnode=curnode-next;if(curnode=NULL) coutnext;else prenode-next=curnode-next;delete curnode; /释放要删除的结点的空间return head;