[Leetcode] Remove Duplicates from Sorted List II
Remove Duplicates from Sorted List II 题解
题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/
Description
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
Solution
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head -> next == NULL)
return head;
ListNode *tempHead = new ListNode(0);
tempHead -> next = head;
ListNode *preNode = tempHead;
ListNode *curNode = head;
while (curNode) {
if (curNode -> next == NULL)
break;
if (curNode -> next != NULL && curNode -> val != curNode -> next -> val) {
preNode = curNode;
curNode = curNode -> next;
} else {
while (curNode -> next != NULL && curNode -> val == curNode -> next -> val) {
curNode = curNode -> next;
}
preNode -> next = curNode -> next;
curNode = preNode -> next;
}
}
return tempHead -> next;
}
};
解题描述
这道题题意是,给出一个排好序的链表,如果某个元素出现重复,则删除所有值为该元素的节点。这道题可能最关键的是边界条件的判断(curNode
到达链表尾),并且考虑到原来的链表头可能被删除,我使用了一个临时链表头tempHead
指向原来的链表头head
,便于在后面直接找到新链表头。
同时还是在第一版中那个问题,在移除节点的时候在没有题目说明的情况下,不应该直接释放链表节点内存,因为节点可能是存在与栈上的而非堆上。