标签:def std \n 表的基本操作 基本 free delete creat null
1 #include <stdio.h> 2 #include <stdlib.h> 3 /* 4 头插法链表的基本操作:创建空链表,插入节点,遍历输出节点数据,求链表长度,查找结点,删除结点。 5 */ 6 typedef struct node 7 { 8 int data; 9 struct node * next; 10 }NODE; 11 //创建空链表 12 NODE * createList() 13 { 14 NODE * head = (NODE *)malloc(sizeof(NODE)); 15 head->next = NULL; 16 17 return head; 18 } 19 //头插法插入新节点 20 void insertNode(NODE * head,int insertData) 21 { 22 NODE * sur = (NODE *)malloc(sizeof(NODE)); 23 sur->data = insertData; 24 25 sur->next = head->next; 26 head->next = sur; 27 28 return; 29 } 30 //遍历输出链表结点数据 31 void traverList(NODE * head) 32 { 33 head = head->next; 34 while(head) 35 { 36 printf("%d\n",head->data); 37 head = head->next; 38 } 39 40 return; 41 } 42 //求链表的长度 43 int lenNodeList(NODE * head) 44 { 45 int len = 0; 46 head = head->next; 47 while(head) 48 { 49 len++; 50 head = head->next; 51 } 52 53 return len; 54 } 55 //查找结点 56 NODE * lookNodeList(NODE *head,int n) 57 { 58 head = head->next; 59 while(head) 60 { 61 if(head->data == n) 62 break; 63 else 64 head = head->next; 65 } 66 return head; 67 } 68 //删除结点 69 void deleteNode(NODE * head,NODE * add) 70 { 71 while(head->next !=add)//找前区 72 { 73 head = head->next; 74 } 75 head->next = add->next; 76 77 free(add); 78 } 79 int main(void) 80 { 81 NODE * head = createList(); 82 83 for(int i = 0;i<100;i++) 84 insertNode(head,i); 85 86 traverList(head); 87 int len = lenNodeList(head); 88 printf("链表长度为:%d\n\n",len); 89 printf("查找数值为33的结点地址\n"); 90 NODE * add = lookNodeList(head,33); 91 if(add == NULL) 92 { 93 printf("没有找到\n"); 94 } 95 else 96 { 97 printf("%d的地址为:%p\n\n",add->data,add); 98 printf("删除33这个结点\n"); 99 deleteNode(head,add); 100 } 101 traverList(head); 102 103 return 0; 104 }
头插法链表的基本操作:创建空链表,插入结点,遍历链表,求链表长度,查找结点,删除结点
标签:def std \n 表的基本操作 基本 free delete creat null
原文地址:https://www.cnblogs.com/wangchaomahan/p/9703034.html