题目
代码(看解析)
这题被自己绕晕了,还是要牢记链表题的两个要点:
- 舍得用变量,千万别想着节省变量,否则容易被逻辑绕晕。
- head 有可能需要改动时,先增加一个 假head,返回的时候直接取 假head.next,这样就不需要为修改 head 增加一大堆逻辑了。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto dummy = new ListNode(0, head); // 虚拟头节点
auto cur = dummy;
while(cur->next && cur->next->next) {
if(cur->next->val == cur->next->next->val) { // 有重复节点
int val = cur->next->val;
while(cur->next && cur->next->val == val) {
cur->next = cur->next->next;
}
} else {
cur = cur->next;
}
}
return dummy->next;
}
};
代码(8.10 二刷看解析)
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{0, head}
cur := dummy
for cur.Next != nil && cur.Next.Next != nil {
if cur.Next.Val == cur.Next.Next.Val {
val := cur.Next.Val
for cur.Next != nil && cur.Next.Val == val {
cur.Next = cur.Next.Next
}
} else {
cur = cur.Next
}
}
return dummy.Next
}
代码(9.13 三刷自解)
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto dummy = new ListNode(0, head);
auto pre = dummy;
auto cur = pre->next;
while(cur) {
if(cur->next && cur->next->val == cur->val) {
while(cur && cur->val == pre->next->val) {
cur = cur->next;
}
pre->next = cur;
} else {
pre = cur;
cur = cur->next;
}
}
return dummy->next;
}
};