您的位置:首页 > 理论基础 > 数据结构算法

数据结构之 线性表---单链表的应用(重复元素删除)

2014-11-13 10:56 411 查看

数据结构上机测试1:顺序表的应用

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


提示

用尽可能少的时间和辅助存储空间。

代码(非常挫啊~~~ 不过将原链表的每个节点都 释放了 节省空间啊 ~~~ 呵呵 ~~~ ):

#include <iostream>
#include <string>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <ctype.h>

using namespace std;

struct node
{
int data;
struct node *next;
};

struct node *creat(int n) //顺序序创建链表
{
int i;
struct node *head, *p, *tail;
head = new node;
head->next = NULL;
tail=head;
for(i=0; i<n; i++)
{
p=new node;
cin>>p->data;
p->next=NULL;

tail->next=p;
tail=p;
}
return head;
}

int main()
{
int n;
cin>>n;
int i, j;
int len;
struct node *head, *w, *q;
struct node *h1, *p, *tail, *dd;

head=creat(n);
//删除重复元素,重复的保留最前面的

h1=new node;
h1->next=NULL;
tail=h1;
len=0;

w=head->next;
delete(head);

for(i=0; i<n; i++)
{
if(h1->next==NULL) //此时链表为空
{
p=new node;
p->data = w->data;
p->next=NULL;
tail->next=p;
tail=p;
len++;
q=w;
w=w->next;
delete(q); //将原链表的节点删除
}
else //若不为空
{
dd=h1->next;
int ff=1;
for(j=0; j<len; j++) //检查是否出现过
{
if(dd->data == w->data )
{
ff=0;
break;
}
dd=dd->next;
}
if(ff==1 )//没出现过
{
p=new node;
p->data = w->data;
p->next=NULL;

tail->next=p;
tail=p;
len++;
q=w;
w=w->next;
delete(q);
}
else if(ff==0 )
{
w=w->next;
}
}
//w=w->next;
}
cout<<len<<endl;
w=h1->next;
for(int k=0; k<len; k++)
{
if(k==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐