欢迎来到天天文库
浏览记录
ID:53453801
大小:33.00 KB
页数:6页
时间:2020-04-03
《头插法和尾插法建立单链表.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include"stdio.h"#include"stdlib.h"typedefstructList{intdata;structList*next;//指针域}List;voidHeadCreatList(List*L)//头插法建立链表{List*s;L->next=NULL;for(inti=0;i<10;i++){s=(structList*)malloc(sizeof(structList));s->data=i;s->next=L->next;//将L指向的地址赋值给S;L->next=s;}}voidTailCreat
2、List(List*L)//尾插法建立链表{List*s,*r;r=L;for(inti=0;i<10;i++){s=(structList*)malloc(sizeof(structList));s->data=i;r->next=s;r=s;}r->next=NULL;}voidDisPlay(List*L){List*p=L->next;while(p!=NULL){printf("%d",p->data);p=p->next;}printf("");}intmain(){List*L1,*L2;L1=(structList*
3、)malloc(sizeof(structList));L2=(structList*)malloc(sizeof(structList));HeadCreatList(L1);DisPlay(L1);TailCreatList(L2);DisPlay(L2);}//头插法创建链表#include#includestructnode{intdata;structnode*next;};//建立只含头结点的空链表structnode*create_list(){structnode*head=NULL
4、;head=(structnode*)malloc(sizeof(structnode));if(NULL==head){printf("memoryoutofuse/n");returnNULL;}head->next=NULL;head->data=0;returnhead;}//头插法建立链表intinsert_form_head(structnode*head,intnum){structnode*head_t=head->next;structnode*new_node=NULL;new_node=(structnode*)m
5、alloc(sizeof(structnode));if(NULL==new_node){printf("memoryoutofuse/n");return-1;}//将新结点插入到链表的最后new_node->data=num;new_node->next=head_t;head->next=new_node;return0;}//打印链表intshow_list(structnode*head){structnode*temp;temp=head->next;while(temp){printf("%d/n",temp->data)
6、;temp=temp->next;}return0;}//按值删除结点,头结点不被删除intdelete_node(structnode*head,intdata){//head_t保存要删除结点的上一个结点structnode*head_t=head;structnode*temp=NULL;if(head==NULL){printf("deletenodefromemptylist!/n");return-1;}//查找删除的结点的前一个结点//如果此处查找的是删除的结点,则需要另加一个指针保存删除结点的前一个指针while(NUL
7、L!=head_t->next){if(data==head_t->next->data)break;head_t=head_t->next;}//如果要删除的结点不存在,直接返回if(NULL==head_t->next){printf("nodenotfound/n");return-1;}//删除操作temp=head_t->next;head_t->next=head_t->next->next;free(temp);return0;}voidmain(intargc,char*argv[]){structnode*head;h
8、ead=create_list();if(NULL==head)printf("create_listerror/n");insert_form_head(head,123);insert_form_hea
此文档下载收益归作者所有