单链表具体主要自编函数
作者:互联网
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 //单链表练习 5 struct Node//定义一个结构体 模板 6 { 7 int data; 8 struct Node* next; 9 } ; 10 struct Node* createlist()//创建新的链表 11 { 12 struct Node* headnode = (struct Node*)malloc(sizeof(struct Node)); 13 headnode->next = NULL; 14 return headnode; 15 } 16 17 18 19 struct Node * createnode(int data)//创建新节点 参数:初始值 20 { 21 struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); 22 newnode->data = data; 23 newnode->next = NULL; 24 return newnode; 25 } 26 27 28 29 30 struct Node * printlist(struct Node* headNode)//打印链表,测试环节 参数:哪个链表 31 { 32 struct Node* Pmove = headNode->next; 33 while (Pmove) 34 { 35 printf("%d",Pmove->data); 36 Pmove = Pmove->next; 37 } 38 printf("\n"); 39 } 40 41 42 43 44 void insertNodeByHead(struct Node* headnode,int data)//创造并头部插入节点 参数:哪个链表,插入节点初始值 45 { 46 struct Node* newnode = createnode(data); 47 newnode->next = headnode->next; 48 headnode->next = newnode; 49 } 50 51 52 53 54 void deleteNode (struct Node* headnode,int posdata)//指定位置删除节点 参数:目标链表,位置数据 55 { 56 struct Node* posnode = headnode->next;//重头开始寻找 57 struct Node* posnodefront = headnode; 58 if (posnode == NULL) 59 printf("无法删除,链表为空\n"); 60 else 61 { 62 while(posnode->data != posdata) 63 { 64 posnodefront = posnode;//移步向下寻找 65 posnode = posnodefront->next; 66 if (posnode == NULL) 67 { 68 printf("没有找到相关信息\n"); 69 return; 70 } 71 } 72 posnodefront ->next = posnode->next;//重组指向 73 free(posnode);//释放空间 74 } 75 } 76 77 int main() 78 { 79 struct Node* list = createlist(); 80 insertNodeByHead(list,1); 81 insertNodeByHead(list,2); 82 insertNodeByHead(list,3); 83 insertNodeByHead(list,4); 84 printlist(list); 85 return 0; 86 }
标签:Node,单链,函数,自编,next,headnode,data,posnode,struct 来源: https://www.cnblogs.com/elapstjtl/p/13781078.html