标签:scribe title sdn free int node content its 保留
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef struct node pnode; 5 struct node 6 { 7 int info; 8 pnode *next; 9 }; 10 11 void create(pnode **head) //创建链表函数 12 { 13 (*head) = (pnode *)malloc(sizeof(pnode)); //创建头结点 14 (*head)->info = 0; //记录链表节点数 15 (*head)->next = nullptr; 16 } 17 18 void add(pnode *head, int val) //链表添加节点函数 19 { 20 head->info ++; //节点数加一 21 22 while (head->next != nullptr) 23 head = head->next; 24 25 pnode *temp = (pnode *)malloc(sizeof(pnode)); //新建节点,存值 26 temp->info = val; 27 temp->next = nullptr; 28 head->next = temp; 29 } 30 31 void show(pnode *head) //打印链表 32 { 33 printf("[%d] ", head->info); //先输出链表节点数 34 head = head->next; 35 36 while (head != nullptr) 37 { 38 printf("%d ", head->info); 39 head = head->next; 40 } 41 } 42 43 void solve(pnode *head) //删去重复节点 44 { 45 if (head == nullptr) //参数为空指针 46 { 47 printf("pointer is nullptr\n"); 48 return; 49 } 50 51 if (head->info == 1) //只有一个节点 52 { 53 printf("list only has one node\n"); 54 return; 55 } 56 57 pnode *pa, *pb, *pc; //用三节点法删除重复节点 58 59 pa = head; 60 pb = pa->next; 61 pc = pb->next; 62 63 while (pc != nullptr) 64 { 65 if (pb->info == pc->info) //发现重复节点 66 { 67 while (pc->info == pb->info) //先删除重复节点序列除首节点外的节点 68 { 69 pnode *temp = pc; 70 71 pc = pc->next; 72 pb->next = pc; 73 free(temp); 74 head->info --; 75 76 if (pc == nullptr) //要记得判空! 77 break; 78 } 79 80 pnode *temp = pb; 81 82 pa->next = pb = pc; //删除该重复节点序列的首节点 83 free(temp); 84 head->info --; 85 86 if (pc != nullptr) 87 pc = pc->next; 88 } 89 90 else //没发现重复节点,则三个节点同时后移一位 91 { 92 pa = pa->next; 93 pb = pb->next; 94 pc = pc->next; 95 } 96 } 97 } 98 99 int main() 100 { 101 pnode *head; 102 103 create(&head); 104 add(head, 2); 105 add(head, 1); 106 add(head, 1); 107 add(head, 1); 108 add(head, 1); 109 add(head, 1); 110 show(head); 111 solve(head); 112 show(head); 113 114 return 0; 115 }
标签:scribe title sdn free int node content its 保留
原文地址:https://www.cnblogs.com/hemeiwolong/p/12468739.html