数据结构实验之链表七:单链表中重复元素的删除
数据结构实验之链表七:单链表中重复元素的删除
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。
Input
第一行输入元素个数 n (1 <= n <= 15);
第二行输入 n 个整数,保证在 int 范围内。
Output
第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。
Sample Input
10 21 30 14 55 32 63 11 30 55 30
Sample Output
10 30 55 30 11 63 32 55 14 30 21 7 30 55 11 63 32 14 21
Hint
Source
不得使用数组!
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-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(" "); 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); 63 q = q->next; 64 for(i=0; i<n; i++) 65 { 66 printf("%d", q->data); 67 if(i==n-1) 68 printf(" "); 69 else 70 printf(" "); 71 q = q->next; 72 } 73 delete1(head, n); 74 75 return 0; 76 }