数据结构上机测试1:顺序表的应用
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
Input
第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。
Output
第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。
Sample Input
12 5 2 5 3 3 4 2 5 7 5 4 3
Sample Output
5 5 2 3 4 7
Hint
用尽可能少的时间和辅助存储空间。
01 |
#include <stdio.h> |
02 |
#include <stdlib.h> |
03 |
04 |
struct node |
05 |
|
06 |
struct node *next; |
07 |
int data; |
08 |
}*p, *q, *head, *tail; |
09 |
int main() |
10 |
{ |
11 |
int i, n; |
12 |
scanf ( "%d" , &n); |
13 |
head = ( struct node *) malloc ( sizeof ( struct node)); |
14 |
head -> next = NULL;tail = head; |
15 |
for (i = 0; i < n; i++) |
16 |
{ |
17 |
p = ( struct node *) malloc ( sizeof ( struct node)); |
18 |
scanf ( "%d" , &p->data);p ->next = NULL;tail ->next = p;tail = p; |
19 |
} |
20 |
tail = head -> next;q = head -> next; |
21 |
for (i = 0; i < n-1; i++) |
22 |
{ |
23 |
while (q -> next!= NULL) |
24 |
{ |
25 |
if (tail ->data == q -> next ->data) |
26 |
{ |
27 |
q->next = q->next->next;n--; |
28 |
} |
29 |
else |
30 |
q = q -> next; |
31 |
} |
32 |
tail = tail->next;q = tail; |
33 |
} |
34 |
tail = head -> next; printf ( "%d\n" , n); |
35 |
for (i = 0; i < n; i++) |
36 |
{ |
37 |
printf ( "%d" , tail -> data); |
38 |
if (tail ->next != NULL) |
39 |
printf ( " " ); |
40 |
else |
41 |
printf ( "\n" ); |
42 |
tail = tail ->next; |
43 |
} |
44 |
return 0; |
45 |
} |
46 |
47 |
48 |
/*************************************************** |
49 |
User name: jk170618李博 |
50 |
Result: Accepted |
51 |
Take time: 0ms |
52 |
Take Memory: 144KB |
54 |
****************************************************/ |