1、题目描述
2、在VS2019上运行
#include <iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode* next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
//空链表
if (pHead == NULL)
return NULL;
ListNode* res = new ListNode(0);
//在链表前加一个表头
res->next = pHead;
ListNode* cur = res;
while (cur->next != NULL && cur->next->next != NULL) {
//遇到相邻两个节点值相同
if (cur->next->val == cur->next->next->val) {
int temp = cur->next->val;
//将所有相同的都跳过
while (cur->next != NULL && cur->next->val == temp)
cur->next = cur->next->next;
}
else
cur = cur->next;
}
//返回时去掉表头
return res->next;
}
};
// 主函数用于测试
int main() {
// 创建链表 1->2->3->3->4->4->5
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(3);
head->next->next->next->next = new ListNode(4);
head->next->next->next->next->next = new ListNode(4);
head->next->next->next->next->next->next = new ListNode(5);
Solution solution;
// 调用删除重复元素的函数
ListNode* result = solution.deleteDuplication(head);
// 打印删除重复元素后的链表
while (result != NULL) {
cout << result->val << " ";
result = result->next;
}
return 0;
}
3、两种方法
(1)方法一:直接比较删除
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
//空链表
if (pHead == NULL)
return NULL;
ListNode* res = new ListNode(0);
//在链表前加一个表头
res->next = pHead;
ListNode* cur = res;
while (cur->next != NULL && cur->next->next != NULL) {
//遇到相邻两个节点值相同
if (cur->next->val == cur->next->next->val) {
int temp = cur->next->val;
//将所有相同的都跳过
while (cur->next != NULL && cur->next->val == temp)
cur->next = cur->next->next;
}
else
cur = cur->next;
}
//返回时去掉表头
return res->next;
}
};
(2)方法二:哈希表法
- step 1:遍历一次链表用哈希表记录每个节点值出现的次数。
- step 2:在链表前加一个节点值为0的表头,方便可能的话删除表头元素。
- step 3:再次遍历该链表,对于每个节点值检查哈希表中的计数,只留下计数为1的,其他情况都删除。
- step 4:返回时去掉增加的表头
class Solution {
public:
ListNode* deleteDuplication(ListNode* head) {
if (head == nullptr)
return nullptr;
unordered_map<int, int> map;
ListNode* cur = head;
//遍历链表统计每个节点值出现的次数
while (cur != nullptr) {
map[cur->val]++;
cur = cur->next;
}
ListNode* res = new ListNode(0);//虚拟头结点
res->next = head;
cur = res;
//再次遍历链表
while (cur->next != nullptr) {
if (map[cur->next->val] != 1)//如果节点值计数不为1
cur->next = cur->next->next;//删去该节点
else
cur = cur->next;
}
return res->next;
}
};