数据结构实验之链表七:单链表中重复元素的删除

https://www.cnblogs.com/6bing/p/3931259.html


题目描述

按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。

输入

第一行输入元素个数n; 
第二行输入n个整数。

输出

第一行输出初始链表元素个数; 
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。

示例输入

10
21 30 14 55 32 63 11 30 55 30

示例输出

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21

提示

 

来源

不得使用数组!

[plain]  view plain copy print ?
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3.   
  4. struct node  
  5. {  
  6.     int data;  
  7.     struct node *next;  
  8. };  
  9.   
  10. void delete1(struct node *head, int n)  
  11. {  
  12.     int i, count=0;  
  13.     struct node *p, *q, *r;  
  14.     p = head->next;  
  15.     q = p;  
  16.     while(p)  
  17.     {  
  18.         while(q->next)  
  19.         {  
  20.            if(p->data == q->next->data)  
  21.            {  
  22.                r = q->next;  
  23.                q->next = r->next;  
  24.                free(r);  
  25.                count++;  
  26.            }  
  27.            else  
  28.             q = q->next;  
  29.         }  
  30.         p = p->next;  
  31.         q = p;  
  32.     }  
  33.     printf("%d\n", n-count);  
  34.     head = head->next;  
  35.     for(i=0; i<n-count; i++)  
  36.     {  
  37.         printf("%d", head->data);  
  38.         if(i==n-count-1)  
  39.             printf("\n");  
  40.         else  
  41.             printf(" ");  
  42.         head = head->next;  
  43.     }  
  44.   
  45. }  
  46.   
  47. int main()  
  48. {  
  49.     int n, i;  
  50.     struct node *head, *p, *q;  
  51.     head = (struct node *)malloc(sizeof(struct node));  
  52.     head->next = NULL;  
  53.     q = head;  
  54.     scanf("%d", &n);  
  55.     for(i=0; i<n; i++)  
  56.     {  
  57.         p = (struct node *)malloc(sizeof(struct node));  
  58.         scanf("%d", &p->data);  
  59.         p->next = head->next;  
  60.         head->next = p;  
  61.     }  
  62.     printf("%d\n", n);  
  63.     q = q->next;  
  64.     for(i=0; i<n; i++)  
  65.     {  
  66.         printf("%d", q->data);  
  67.         if(i==n-1)  
  68.             printf("\n");  
  69.         else  
  70.             printf(" ");  
  71.         q = q->next;  
  72.     }  
  73.     delete1(head, n);  
  74.   
  75.     return 0;  
  76. }  


每天训练发现我比别人做的好慢,但是理解的更深刻,如果一开始学一个新知识点就搜模板,那么这样的人是走不远的,毕业之后带走的只有思维,什么荣誉,奖杯都已经不重要了。

猜你喜欢

转载自blog.csdn.net/sinat_35297665/article/details/80464463