目录
题目
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
代码
#include<iostream>
#include<set>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Create(int n)
{
Node* h, * p, * s;
h = new Node;
h->next = NULL;
p = h;
for (int i = 0; i < n; i++)
{
s = new Node;
cin >> s->data;
p->next = s;
p = s;
}
p->next = NULL;
return h;
}
void Print(Node* h)
{
Node* p = h->next;
while (p != NULL)
{
cout << p->data << "\t";
p = p->next;
}
cout << endl;
}
Node* Deletecommon(Node* head1)
{
if (head1 == NULL)
return head1;
set<int> st;
Node* pre = head1, * cur = head1->next;
while (cur != NULL)
{
if (pre->data == cur->data)
{
st.insert(pre->data);
}
cur = cur->next;
pre = pre->next;
}
Node* vhead = new Node;
vhead->next = head1;
pre = vhead;
cur = head1;
while (cur != NULL)
{
if (st.count(cur->data))
{
cur = cur->next;
pre->next=cur;
}
else
{
pre = pre->next;
cur = cur->next;
}
}
return vhead->next;
}
int main()
{
Node* head1 = new Node;
head1->next = NULL;
Node* head2 = new Node;
head2->next = NULL;
int i;
cout << "请输入链表的结点个数:";
cin >> i;
cout << "请输入结点值:";
head1 = Create(i);
cout << "删除相同结点之后的链表为:";
head2 = Deletecommon(head1);
Print(head2);
return 0;
}
运行结果:
知识点
1.(47条消息) c++ stl set容器常用用法_shuaizhijun的博客-CSDN博客_c++容器set
(1)set<int> st;
Node* pre = head1, * cur = head1->next;
(2)while (cur != NULL)
{
if (pre->data == cur->data)
{
st.insert(pre->data);
}
cur = cur->next;
pre = pre->next;
}
(3)Node* vhead = new Node;
vhead->next = head1;
pre = vhead;
cur = head1;
(4) while (cur != NULL)
{
if (st.count(cur->data))
{
cur = cur->next;
pre->next=cur;
}
else
{
pre = pre->next;
cur = cur->next;
}
}