题目描述
删除带有头结点的有序链表中值相同的结点,使之只保留一个。
输入:第一行输入链表长度;第二行输入链表结点中的数据。
输出:删除值相同的结点后的有序链表(输出头结点,用 “Head” 表示)。
样例输入
8
1 2 2 3 4 4 4 5
样例输出
Head->1->2->2->3->4->4->4->5
Head->1->2->3->4->5
相关知识请参考C++实现线性表基本操作
参考代码
#include <iostream>
using namespace std;
struct node{
int data;
node * next;
};
node *insertTail(node *h, node *t);
void printList(node *h);
void delList(node *h);
void removeRep(node *h){
node *p = h, *q = h->next;
while(q){
while(q->data == p->data) {
if(q->next == NULL){
p->next = NULL;
return;
}
q = q->next;
}
p -> next = q;
p = q;
q = q->next;
}
}
int main()
{
int n,i;
node *t;
node *head=NULL; // 头指针为NULL,表示线性表为空,结点数为0
// 输入结点数
cin>>n;
for(i=0;i<n;i++)
{
// 为新节点动态分配空间
t = new node;
cin>>t->data; // 输入结点数据
t->next=NULL; // 结点指针域值为空
// 调用函数插入结点
head = insertTail(head, t);
}
// 输出链表
printList(head);
// 删除结点,释放空间
removeRep(head);
printList(head);
delList(head);
return 0;
}
node *insertTail(node *h, node *t)
{
if(h==NULL){
t->next = NULL; //头指针为空则将t作为新的头指针
return t;
}
node *p = h;
while(p->next != NULL){
p = p -> next;
} //找到链表尾
p -> next = t;
return h;
}
void printList(node *h)
{
cout<<"Head->";
while(h)
{//h为真,即h指向的结点存在,则输出该结点的数据
cout<<h->data;//输出结点数据
if(h->next) cout<<"->";
h=h->next; //将该结点的指针域赋值给h,h就指向了下一个结点
}
cout<<endl; //输出换行符
}
void delList(node *h)
{
node *p=h; //指针p指向头结点,第一个要删除的结点
while(p) //这个结点是存在的
{
h = h->next; //头指针h指向下一个结点(下一个结点的地址存在当前结点的指针域中,即h->next中
delete p; //删除p指向的结点
p = h; //p指向当前的头结点,即下一个要删除的结点
}
}