单链表的插入操作实现
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct LinkList 5 { 6 int data; 7 struct LinkList *next; 8 }LinkList; 9 10 void CreateLinkList(LinkList *&L,int n, int *array) 11 { 12 L =(LinkList*)malloc(sizeof(LinkList)); //先创建一个带头结点的单链表 13 L->next = NULL; 14 LinkList * r = L; //r指针始终指向链表的最后一个节点 15 for (int i = 0; i < n; ++i) 16 { 17 LinkList * p =(LinkList*)malloc(sizeof(LinkList)); 18 p->data = *array++; 19 //将新增的节点用尾插法插入到链表中 20 p->next = r->next; 21 r->next = p; 22 r = p; 23 } 24 25 } 26 27 void InsertLinkList(LinkList *&L, int n, int item, int data) 28 { 29 if(item > n || item < 0) 30 { 31 printf("error!"); 32 exit(-1); 33 } 34 else 35 { 36 LinkList *p = L; 37 for (int i = 0; i < item-1; ++i) 38 { 39 p = p->next; 40 } 41 42 LinkList * node =(LinkList*)malloc(sizeof(LinkList)); 43 node->data = data; 44 node->next = p->next; 45 p->next = node; 46 } 47 } 48 49 void DisLinkList(LinkList *L) 50 { 51 LinkList *p = L->next; 52 while(p!=NULL) 53 { 54 printf("%d ",p->data); 55 p = p->next; 56 } 57 } 58 59 int main(int argc, char const *argv[]) 60 { 61 /*int n = 5; 62 int arry[]={1,2,3,4,5}; 63 int item = 3; 64 int data = 6;*/ 65 66 int n,item,data; 67 int *arry; 68 69 scanf("%d",&n); 70 arry = (int*)malloc(n*sizeof(int)); 71 for (int i = 0; i < n; ++i) 72 { 73 scanf("%d",&arry[i]); 74 } 75 scanf("%d",&item); 76 scanf("%d",&data); 77 78 LinkList * L; 79 CreateLinkList(L,n,arry); 80 InsertLinkList(L,n,item,data); 81 DisLinkList(L); 82 return 0; 83 }