关于有头结点链表的创建算法及基础功能打的实现

  

这里是有头结点的链表创建:


1
#include<stdio.h> 2 #include<stdlib.h> 3 typedef struct Link 4 { 5 int data; 6 struct Link *next; 7 }lk;//定义lk为struct link类型; 8 9 lk *initlink()//链表的建立,返回值为lk类型的指针; 10 { 11 int i,n; 12 lk *head=(lk*)malloc(sizeof(lk));//先用头指针head申请一段内存 13 lk *temp=head; 14 printf("请你输入你要的十个数字:\n"); 15 for(i=0;i<10;i++) 16 { 17 lk *a=(lk*)malloc(sizeof(lk));//开始申请结点,每个结点包含数据域和指针域; 18 scanf("%d",&n); 19 a->data=n;//使第一个结点接收数据; 20 a->next=NULL; 21 temp->next=a;//这里的temp相当于是第三个辅助用的结点,用来递增遍历输入元素; 22 temp=temp->next; 23 24 } 25 return head; 26 } 27 28 void display(lk *head) 29 { 30 lk *temp=head; 31 while(temp->next)//因为此算法是没有头节点的,所以要从头指针指向的下一个结点开始,而不是temp; 32 { 33 temp=temp->next; 34 printf("%d ",temp->data); 35 } 36 printf("\n"); 37 } 38 39 lk *insertdata(lk *head,int data,int add) 40 { 41 int i; 42 lk *temp=head; 43 for(i=1;i<add;i++) 44 { 45 if(temp==NULL) 46 { 47 printf("位置无效\n"); 48 return head; 49 } 50 temp=temp->next; 51 }//一直将temp移动到要插入的那个位置的前一个结点; 52 53 lk *c=(lk*)malloc(sizeof(lk));//创造第三方指针接受新数据; 54 c->data=data; 55 c->next=temp->next; 56 temp->next=c;//要先让c的指针域指向插入的指针,再将c和上一个结点连起来; 57 return head; 58 } 59 60 lk *deldata(lk *head,int add) 61 { 62 int i; 63 lk *temp=head; 64 for(i=1;i<add;i++) 65 { 66 temp=temp->next; 67 } 68 lk *d=temp->next; 69 temp->next=temp->next->next; 70 free(d);//让d记录刚才的数据防止丢失,然后再释放内存; 71 return head; 72 } 73 int chazhao(lk *head,int data) 74 { 75 lk *e=head; 76 int i; 77 i=1; 78 while(e->next) 79 { 80 e=e->next; 81 if(e->data==data) 82 { 83 return i; 84 } 85 i++; 86 } 87 return -1; 88 } 89 90 int main() 91 { 92 int weizhi,shuzi; 93 int t,m; 94 lk *p; 95 printf("这个程序你要玩几遍勒?\n输入他:"); 96 scanf("%d",&m); 97 while(m--) 98 { 99 printf("欢迎使用邱哥的程序\n"); 100 p=initlink(); 101 display(p); 102 103 printf("输入你要在第几个位置插入数字几:\n"); 104 scanf("%d %d",&weizhi,&shuzi); 105 insertdata(p,shuzi,weizhi); 106 display(p); 107 108 printf("输入你要删除第几个位置的元素:\n"); 109 scanf("%d",&weizhi); 110 deldata(p,weizhi); 111 display(p); 112 113 printf("输入你要查找的数字:\n"); 114 scanf("%d",&shuzi); 115 t=chazhao(p,shuzi); 116 if(t==-1) 117 printf("不好意思,没有找到\n"); 118 else 119 printf("它的位置在第%d个。\n",t); 120 printf("谢谢使用\n"); 121 } 122 123 return 0; 124 }

 

posted @ 2019-03-08 20:21  AQhhhhh  阅读(1030)  评论(0编辑  收藏  举报