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.
For example,
Given1->2->3->3->4->4->5
, return1->2->5
.
Given1->1->1->2->3
, return2->3
.
移除给定链表中重复出现的节点。
代码如下:
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function ListNode dummy(0); dummy.next = head; ListNode *pre = &dummy, *cur = head; while (cur) { int i = cur->val; if (cur->next && cur->next->val == i) { while (cur && cur->val == i) { pre->next = cur->next; delete cur; cur = pre->next; } } pre = cur; cur = cur->next; } return dummy.next; } };