Skip to content

Commit b9703ba

Browse files
authored
up 82 删除排序链表中重复元素II (重复的都不保留)
1 parent daf3932 commit b9703ba

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

algorithms/algo_notes/链表专题.md

+33
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,39 @@ ListNode* Delete(ListNode* head, int value) {
5656
//输入的链表为空,或者操作可能会产生新的头结点,这些都是应聘者在面试的时候特别容易忽略的点,如果合理使用哨兵节点,就可以不再处理这些节点
5757
//使用哨兵节点可以简化创建或删除链表头节点操作代码
5858
```
59+
## 82 删除排序链表中重复元素II (重复的都不保留)
60+
61+
```c++
62+
class Solution {
63+
public:
64+
ListNode* deleteDuplication(ListNode* pHead) {
65+
/*
66+
非递归的代码:
67+
1. 首先添加一个头节点,以方便碰到第一个,第二个节点就相同的情况
68+
2.设置 pre ,last 指针, pre指针指向当前确定不重复的那个节点,而last指针相当于工作指针,一直往后面搜索。
69+
*/
70+
if (!pHead) return nullptr;
71+
ListNode* head = new ListNode(0);
72+
head->next = pHead;
73+
ListNode* pre = head;
74+
ListNode* last = head->next;
75+
while(last) {
76+
if (last->next && last->next->val == last->val) {
77+
//找到最后一个相同节点
78+
while(last->next && last->val == last->next->val) {
79+
last = last->next;
80+
}
81+
pre->next = last->next;
82+
last = last->next;
83+
} else {
84+
pre = pre->next;
85+
last = last->next;
86+
}
87+
}
88+
return head->next;
89+
}
90+
};
91+
```
5992

6093
## 剑指 Offer II 021. 删除倒数第 K 个节点
6194

0 commit comments

Comments
 (0)