Problem Description
按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。
Input
第一行输入元素个数 n (1 <= n <= 15);
第二行输入 n 个整数,保证在 int 范围内。
Output
第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。
Example Input
10 21 30 14 55 32 63 11 30 55 30
Example Output
10 30 55 30 11 63 32 55 14 30 21 7 30 55 11 63 32 14 21
01 | #include<stdio.h> |
02 | #include<stdlib.h> |
03 | struct node |
04 | { |
05 | int date; |
06 | struct node *next; |
07 | } *head, *p, *q, *t; |
08 | int main() |
09 | { |
10 | int n, i; |
11 | scanf ( "%d" , &n); |
12 | head = ( struct node *) malloc ( sizeof ( struct node)); |
13 | head -> next = NULL; |
14 | for (i = 0; i < n; i++) |
15 | { |
16 | p = ( struct node *) malloc ( sizeof ( struct node)); |
17 | scanf ( "%d" , &p -> date); |
18 | p -> next = head -> next; |
19 | head -> next = p; |
20 | } |
21 | printf ( "%d\n" , n); |
22 | p = head -> next; |
23 | while (p != NULL) |
24 | { |
25 | if (p -> next != NULL) |
26 | { |
27 | printf ( "%d " , p -> date); |
28 | } |
29 | else |
30 | { |
31 | printf ( "%d\n" , p -> date); |
32 | } |
33 | p = p -> next; |
34 | } |
35 | q = ( struct node *) malloc ( sizeof ( struct node)); |
36 | p = head -> next; |
37 | while (p && p -> next != NULL) |
38 | { |
39 | q = p; |
40 | t = q -> next; |
41 | while (t != NULL) |
42 | { |
43 | if (t -> date == p -> date) |
44 | { |
45 | q -> next = t -> next; |
46 | free (t); |
47 | t = q -> next; |
48 | n--; |
49 | } |
50 | else |
51 | { |
52 | q = t; |
53 | t = t -> next; |
54 | } |
55 | } |
56 | p = p -> next; |
57 | } |
58 | printf ( "%d\n" , n); |
59 | p = head -> next; |
60 | while (p != NULL) |
61 | { |
62 | if (p -> next != NULL) |
63 | { |
64 | printf ( "%d " , p -> date); |
65 | } |
66 | else |
67 | { |
68 | printf ( "%d\n" , p -> date); |
69 | } |
70 | p = p -> next; |
71 | } |
72 | return 0; |
73 | } |