编码实现环状单向链表(尾指针直接指向头指针,中间没有空节点),去除连续的重复元素的操作。

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 #define PERR    printf("FILE: %s, FUNCTION: %s, LINE: %d
",
  5                                     __FILE__, __func__, __LINE__)
  6 
  7 struct Tnode
  8 {
  9     struct Tnode *next;
 10     int value;
 11 };
 12 
 13 void Del_Repeat_Node(struct Tnode **head)
 14 {
 15     if(NULL == head || NULL == *head){
 16         return;
 17     }
 18 
 19     struct Tnode *pnode = *head, *fnode = NULL;
 20     
 21     while(pnode ->next != *head)
 22     {
 23         if(pnode->next->value == pnode->value)
 24         {
 25             fnode = pnode->next;
 26             pnode->next = fnode->next;
 27             free(fnode);
 28             continue;
 29         }
 30         pnode = pnode->next;
 31     }
 32     if((*head)->next == *head)//当(或删除后只有)只有一个节点
 33         return ;
 34     if(pnode->value == (*head)->value)//当尾结点的value也等于头结点的value
 35     {
 36         fnode = *head;
 37         pnode->next = fnode->next;
 38         *head = pnode;
 39         free(fnode);
 40     }
 41 }
 42 
 43 //以下为测试代码
 44 //插入结点到表头
 45 int Insert_to_head(struct Tnode **head, int value)
 46 {
 47     struct Tnode *new_node = 
 48             (struct Tnode *)calloc(1, sizeof(struct Tnode));
 49     if(NULL == new_node){
 50         perror("malloc");
 51         return -1;
 52     }
 53     //填充结点信息
 54     new_node->value = value;
 55     new_node->next = NULL;
 56 
 57     if(*head == NULL)
 58     {
 59         *head = new_node;
 60         (*head)->next  = *head;
 61     }
 62     else
 63     {
 64         struct Tnode *tail = *head;
 65         while(tail->next != *head)
 66             tail = tail->next;
 67 
 68         new_node->next = *head;
 69         tail->next = new_node;
 70         *head = new_node;
 71     }
 72     return 0;
 73 }
 74 
 75 //遍历链表
 76 int traverse_link(struct Tnode *head)
 77 {
 78     if(NULL == head)
 79         return -1;
 80     struct Tnode *pnode = head;
 81     while(pnode->next != head)
 82     {
 83         printf("%d	", pnode->value);
 84         pnode = pnode->next;
 85     }
 86 
 87     printf("%d
", pnode->value);
 88 
 89     return 0;
 90 }
 91 
 92 
 93 int main()
 94 {
 95     int i;
 96     struct Tnode *head = NULL;
 97 
 98     Insert_to_head(&head, 1);
 99 
100     Insert_to_head(&head, 1);
101     
102 
103     Insert_to_head(&head, 1);
104     Insert_to_head(&head, 2);
105     Insert_to_head(&head, 2);
106     
107     Insert_to_head(&head, 1);
108 
109     traverse_link(head);
110 
111     Del_Repeat_Node(&head);
112 
113     traverse_link(head);
114 
115     return 0;
116 }
原文地址:https://www.cnblogs.com/xuyh/p/3489400.html