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;
}