1. 程式人生 > >leetcode82. Remove Duplicates from Sorted List II

leetcode82. Remove Duplicates from Sorted List II

sorted init lis 虛擬節點 for dup leetcode code nod

利用虛擬節點進行刪除結點,pre始終指向不重復的錢一個元素,一開始指向虛擬結點。如果遇到重復結點就全部刪除再與pre相連接.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode
* dummyNode; dummyNode = new ListNode(0); dummyNode->next = head; ListNode* pre; pre = dummyNode; ListNode* cur; cur = head; if (head == NULL) return NULL; while (cur->next!=NULL)//pre指向沒重復的前一個元素,cur指向當前元素 {
if(cur->next->val == cur->val) { if(cur->val == cur->next->val) { int val = cur->val; while (cur!=NULL&&cur->val == val) { ListNode* delNode; delNode
= cur; cur = cur->next; delete delNode; } pre->next = cur; if (cur == NULL) break; } } else { pre = cur; cur = cur->next; } } return dummyNode->next; } };

leetcode82. Remove Duplicates from Sorted List II