数据结构上机测试1:顺序表的应用
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
输入
第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。
第二行依次输入顺序表初始存放的n个元素值。
输出
第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。
第二行依次输出完成删除后的顺序表元素。
示例输入
12 5 2 5 3 3 4 2 5 7 5 4 3
示例输出
5 5 2 3 4 7
提示
用尽可能少的时间和辅助存储空间。
解题方法一:使用数组
很简单,代码也很短,比较好理解。
代码如下:
#include<iostream>
//#include<cstring>
using namespace std;
int main()
{
int n;
int a[1000]={0},b[1000]={0};//memset(a, 0, sizeof(int)*1000);
cin>>n;
int m=n;
for(int i=0;i<n;i++)
cin >>a[i];
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if(a[i]==a[j]&&!b[j])
{
m--;
b[j]=1;
}
cout<<m<<endl;
for(int i=0;i<n;i++)
if(!b[i]&&m!=1)
{
cout<<a[i]<<" ";
m--;
}
else if(!b[i])
{
cout<<a[i];
m--;
}
return 0;
}
方法二:链表
先建立链表,进行然后进行删除。
代码如下:
#include<iostream>
#include<cstdlib>
using namespace std;
int n;
struct node
{
int data;
node *next;
};
node * creat(int n) //创建顺序链表
{
node *p,*head,*tail;
head=(node *)malloc(sizeof(node ));
head->next=NULL;
tail=head;
for(int i=0; i<n; i++)
{
p=(node*)malloc(sizeof(node));
cin >>p->data;
tail->next=p;
tail=p;
}
p->next=NULL;
return head;
}
node *delet(node* head) //删除重复元素
{
node *p,*q,*t;
p=head->next;
while(p!=NULL)
{
t=p;
q=p->next;
while(q!=NULL)
if(q->data==p->data)
n--,t->next=q->next,q=t->next;
else q=q->next,t=t->next;
p=p->next;
}
return head;
}
int print(node *head)
{
node *p=head->next;
while(p!=NULL)
{
if(p->next!=NULL)
cout <<p->data<<" ";
else cout <<p->data<<endl;
p=p->next;
}
return 0;
}
int main()
{
cin >>n;
node *q=creat(n);
q=delet(q);
cout <<n<<endl;
print(q);
return 0;
}