1 #include<stdio.h>//单链表的定义和基本操作 2 #include<stdlib.h>//malloc函数所需要的头文件 3 #include<stddef.h>//定义NULLL的头文件 4 5 typedef struct LNode//定义单链表的节点 6 { 7 int data; 8 struct LNode*next; 9 }LNode; 10 11 void Creatlinklist(LNode *&L,int a[],int n)//尾插法建立单链表 12 { 13 int i; 14 LNode*r; 15 LNode*p; 16 L=(LNode*)malloc(sizeof(LNode)); 17 L->next=NULL; 18 r=L; 19 for(i=0;i<n;i++) 20 { 21 p=(LNode*)malloc(sizeof(LNode)); 22 p->data=a[i]; 23 r->next=p; 24 r=r->next; 25 } 26 r->next =NULL; 27 } 28 29 void Creatlinklist2(LNode *&L,int a[],int n)//头插法建立单链表 30 { 31 int i; 32 LNode*p; 33 L=(LNode*)malloc(sizeof(LNode)); 34 L->next=NULL; 35 for(i=0;i<n;i++) 36 { 37 p=(LNode*)malloc(sizeof(LNode)); 38 p->data=a[i]; 39 p->next=L->next; 40 L->next=p; 41 } 42 } 43 44 45 46 int FindAndDeletelem(LNode *&L,int x)//寻找并删除等于x的元素成功返回1失败返回0 47 { 48 LNode *p; 49 LNode *q; 50 p=L; 51 while(p->next!=NULL) 52 { 53 if(p->next->data==x) 54 break; 55 p=p->next ; 56 } 57 if(p->next==NULL) 58 return 0; 59 else 60 { 61 q=p->next; 62 p->next=q->next; 63 free(q); 64 return 1; 65 } 66 } 67 68 69 int Insertlist(LNode *&L,int i,int a)//在第i个元素的位置插入数据a(有头结点) 70 { 71 int j; 72 LNode *p,*q; 73 q=L; 74 p=(LNode*)malloc(sizeof(LNode)); 75 p->data=a; 76 for(j=1;j<i;q=q->next) 77 j++; 78 p->next=q->next ; 79 q->next=p; 80 return 1; 81 } 82 83 84 85 int main()//测试程序 86 { 87 LNode *L; 88 int a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 89 Creatlinklist(L,a,10); 90 FindAndDeletelem(L,5); 91 Insertlist(L,5,22); 92 printf("%d",L->next->next->next->next->next->data); 93 return 0; 94 }