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
用尽可能少的时间和辅助存储空间。
方法一:
#include <iostream>
#include <stdio.h>
using namespace std;
int a[1010];
int main() {
int n;
while(~scanf("%d", &n)) {
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
if(a[i] == a[j]) {
for(int k = j; k < n - 1; k++) {
a[k] = a[k + 1];
}
n--;
j--;
}
}
}
printf("%d\n", n);
for(int i = 0; i < n; i++) printf(i == 0 ? "%d" : " %d", a[i]);
printf("\n");
}
return 0;
}
方法二:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int n;
struct node {
int data;
struct node *next;
};
struct node *creat() {
struct node *head, *tail, *p;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
tail = head;
for(int i = 0; i < n; i++) {
p = (struct node*)malloc(sizeof(struct node));
scanf("%d", &p->data);
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
};
int main() {
struct node *head, *p, *q, *tail;
while(~scanf("%d", &n)) {
head = creat();
tail = head->next;
p = tail->next;
q = tail;
while(tail->next != NULL) {
while(p != NULL) {
if(tail->data == p->data) {
q->next = p->next;
free(p);
p = q->next;
n--;
} else {
q = p;
p = p->next;
}
}
tail = tail->next;
q = tail;
p = tail->next;
}
printf("%d\n", n);
p = head->next;
while(p != NULL) {
if(p->next == NULL)
printf("%d\n", p->data);
else
printf("%d ", p->data);
p = p->next;
}
}
return 0;
}