1. 程式人生 > >【LeetCode】82. Remove Duplicates from Sorted List II(C++)

【LeetCode】82. Remove Duplicates from Sorted List II(C++)

地址:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

題目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

理解:

一個有序連結串列中,刪除重複值,只留下那些單獨的元素。

實現:

pre:目前已經處理的部分的尾指標
p:工作指標,指向要開始處理部分的第一個位置
q:工作指標,最後會指向不等於p的第一個位置

class Solution {
public:
	ListNode* deleteDuplicates(ListNode* head) {
		ListNode* pre = nullptr;
		ListNode* p = head;
		while (p)
{ ListNode* q = p->next; while (q && q->val == p->val) q = q->next; // if no duplicates, add p to down area if (q == p->next) { pre = p; } else { // has down area, add to the back if (pre) { pre->next = q; } // don't have down area, need to modify the head pointer
else { head = q; } } p = q; } return head; } };