【LeetCode练习题】Remove Duplicates from Sorted List II

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,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

移除给定链表中重复出现的节点。

代码如下:

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode dummy();
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;
}
};
上一篇:Remove Duplicates from Sorted List II


下一篇:当我们直接打印定义的对象的时候,隐含的是打印toString()的返回值。