编写一个能删除链表中值相同的多余元素的小程序。
已知一个有序排列的单向链表,编写一个程序,删除链表中所有值相同的多余元素(即:使得运算后的链表中所有元素的值均不相同)
输入输出:
首先输入链表长度,例如14,然后输入相应的值,例如1、2、3、3、4、5、6、6、7、8、9、9、10 、10
输出为1、2、3、4、5、6、7、8、9、10
效果如下:
输入:
14
1 2 3 3 4 5 6 6 7 8 9 9 10 10
输出:
1 2 3 4 5 6 7 8 9 10
//不使用链表
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
if(a[i]==a[i+1])
{
continue;
}
else
{
cout<<a[i]<<" ";
}
}
}
或
#include<iostream>
using namespace std;
struct node
{
int num;
node *nextNode;
};
node *creatList(int count,int a[])
{
int i;
node *p1,*p0, *head;
p1=p0=head=new node;
p1->num=a[0];
for(i=1; i<count; i++)
{
node *p0=new node;
p0->num=a[i];
p1->nextNode=p0;
p1=p0;
}
p1->nextNode=NULL;
return head;
}
node *deleteNode(node *head)
{
node *p, *p0=new node;
p=head;
p0=head->nextNode;
if(p0==NULL)
{
return head;
}
while(p->nextNode!=NULL)
{
if(p->num==p0->num)
{
if(p0->nextNode!=NULL)
{
p0=p0->nextNode;
p->nextNode=p0;
}
else
{
p->nextNode=NULL;
}
}//删除相同的节点
p=p0;
if(p0->nextNode!=NULL)
{
p0=p0->nextNode;
}
}
return head;
}
int main()
{
int i,n;
cin>>n;
int *array = new int[n];
for(i=0; i<n; i++)
{
cin>>array[i];
}
node *head = new node ;
head = creatList(n,array);
head = deleteNode(head);
node *tail = head;
while(tail!= NULL)
{
cout<<tail->num<<" ";
tail = tail->nextNode;
}
return 0;
}