顺序表的应用
Time Limit: 1000MS Memory limit: 65536K
题目描述
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
输入
第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。
输出
第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。
示例输入
12
5 2 5 3 3 4 2 5 7 5 4 3
示例输出
5
5 2 3 4 7
///Accode
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
node *next;
};
void ffree(node *l) ///释放内存
{
node *p,*x;
p=l;
while (p)
{
x=p;
p=p->next;
free(x);
}
}
struct node *Delete(node *head,int &n)
{
node *p,*tail,*a;
tail=head->next;
while(tail)
{
p=tail;///p is 前驱
a=p->next;
while(a)
{
if (a->data == tail->data)
{
p->next=a->next;
///head->len--;
n--;
}
else
{
p=p->next;
}
a=a->next;
}
tail=tail->next;
}
return head;
}
struct node *creat(int n) ///顺序建表
{
int i;
node *head,*tail,*p;
head=new node;
tail=head;
for (i=1; i<=n; i++)
{
p=new node;
cin>>p->data;
tail->next=p;
p->next=NULL;
tail=p;
}
///head->len=n;
return head;
}
struct node *print(node *h)
{
node *p;
p=h->next;
while(p)
{
cout<<p->data;
if (p->next)
{
cout<<" ";
}
p=p->next;
}
cout<<endl;
}
struct node *inall(node *l,node *l2)///归并到 l
{
node *a,*b,*tail,*p;
int x;
a=l->next;
b=l2->next;
tail=l;
while(a&&b)
{
if (a->data <= b->data)
{
x=a->data;
p=new node;
p->data=x;
tail->next=p;
p->next=NULL;
tail=p;
a=a->next;
}
else
{
x=b->data;
p=new node;
p->data=x;
tail->next=p;
p->next=NULL;
tail=p;
b=b->next;
}
}
if (a==NULL)
{
while(b)
{
tail->next=b;
b->next=NULL;
tail=b;
b=b->next;
///break;
}
}
else if(b==NULL)
{
while(a)
{
tail->next=a;
a->next=NULL;
tail=a;
a=a->next;
///break;
}
}
ffree(l2);
return l;
}
struct node *oppositcreat()///逆序建表 遇到-1结束
{
int x;
node *head,*p,*tail;
head= new node;
p=new node;
p->next=NULL;
tail=p;
cin>>p->data;
while (1)
{
cin>>x;
if (x!=-1)
{
p=new node;
p->data=x;
head->next=p;
p->next=tail;
tail=p;
}
else break;
}
return head;
}
int main()
{
int n,t;
node *l;
cin>>n;
l=creat(n);
l=Delete(l,n);
cout<<n<<endl;
print(l);
ffree(l);
return 0;
}