leetcode82. Remove Duplicates from Sorted List II
2018-09-24 02:02 legend聪 阅读(146) 评论(0) 编辑 收藏 举报利用虚拟节点进行删除结点,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; } };