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

数据结构之 线性表---单链表的操作B(先逆序+再删除重复元素)

2014-11-13 10:42 471 查看

数据结构上机测试2-2:单链表操作B

Time Limit: 1000MS Memory limit: 65536K

题目描述

按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。

输入

第一行输入元素个数n;

第二行输入n个整数。

输出

第一行输出初始链表元素个数;

第二行输出按照逆位序所建立的初始链表;

第三行输出删除重复元素后的单链表元素个数;

第四行输出删除重复元素后的单链表。

示例输入

10
21 30 14 55 32 63 11 30 55 30


示例输出

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21

代码(好搓~~~啊~~~,凑和着看吧):


#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 *nicreat(int n) //逆序创建链表
{
int i;
struct node *head, *p;
head = new node;
head->next = NULL;

for(i=0; i<n; i++)
{
p=new node;
cin>>p->data;
p->next=head->next;
head->next=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=nicreat(n);
cout<<n<<endl;
w=head->next;

for(i=0; i<n; i++)
{
if(i==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;
//删除重复元素,重复的保留最前面的

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: