数据结构上机测试1:顺序表的应用
Time Limit: 1000 msMemory Limit: 65536 KiB
Problem Description
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
Input
第一行输入表的长度n;
第二行依次输入顺序表初始存放的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
用尽可能少的时间和辅助存储空间。
Source
#include<bits/stdc++.h>
using namespace std;
struct node{
int date;
struct node *next;
};
int main(){
int n;
struct node *head, *tail, *p, *q, *t;
head = (struct node *)malloc(sizeof(struct node));
head -> next = NULL;
cin>>n;
int sum = n;
tail = head;
while(n--){
p = (struct node*)malloc(sizeof(struct node));
cin>>p -> date;
p -> next = tail -> next;
tail -> next = p;
tail = p;
}
//p = head -> next;
q = head -> next;
while(q){
t = q;
p = q -> next;
while(p){
if(q -> date == p -> date){
//t -> next = q -> next;
//free(q);
t -> next = p -> next;
//q = t -> next;
//free(t);
sum--;
p = p -> next;
}
else{
t = t -> next;
p = p -> next;
}
}
q = q -> next;
}
p = head -> next;
cout<<sum<<endl;
while(p){
if(p == head -> next){
printf("%d", p -> date);
}
else printf(" %d", p -> date);
p = p -> next;
}
printf("\n");
return 0;
}