Problem F: 删除相同元素(线性表)
Description
(线性表)在一个递增有序的线性表中,有数值相同的元素存在。若存储方式为单链表,设计算法去掉数值相同的元素,使表中不再有重复的元素。
Input
输入长度:6
输入数据:2 3 4 5 5 7
Output
2 3 4 5 7
Sample Input
68 9 10 11 22 22
Sample Output
8 9 10 11 22
HINT
#include <iostream>
#define NULL 0
using namespace std;
struct student
{
int num;
student *next;
};
int n;
student *creat(int m)
{
student *head,*p1,*p2;
p1=p2=new student;
cin>>p1->num;
head=NULL;
n=0;
while(p1->num!=NULL)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=new student;
if(n==m)
{break;}
else
cin>>p1->num;
}
p2->next=NULL;
return(head);
}
void print(student *head)
{
student *p;
p=head;
if(head!=NULL)
do
{
cout<<p->num<<" ";
p=p->next;
}while(p!=NULL);
}
student *del(student *head)
{
student *p1,*p2;
p2=head;
do{
p1=p2;
p2=p2->next;
if(p2->num==p1->num)//由p1,p2来确定链表中相邻两值是否相同
{
p1->next=p2->next;
}
}while(p2->next!=NULL);
return (head);
}
int main()
{
int m,num;
cin>>m;
student *head;
student *creat(int);
void print(student *);
student *del(student *);
head=creat(m);
head=del(head);
print(head);
return 0;
}