LeetCode 82 Remove Duplicates from Sorted List II（从已排序链表中移除重复元素）（Linked List）（*）

原文

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.

分析

1 -> 1 -> 2 -> 3 -> NULL

x -> 1 -> 1 -> 3 -> NULL

return x->next;

代码

C Plus Plus

ListNode *deleteDuplicates(ListNode *head) {

while (p != NULL && p->next != NULL) {
if (p->val != p->next->val) {
c = c->next;
p = p->next;
} else {
while (p->next != NULL && p->val == p->next->val) {
p = p->next;
}
p = p->next;
c->next = p;
}
}
}

updated at 2016/08/14

ListNode* deleteDuplicates(ListNode *head) {
ListNode *c = newHead, *p = c->next;

while (c->next && c->next->next) {
if (c->next->val == c->next->next->val) {
p = p->next;
while (p->next && p->val == p->next->val) {
p = p->next;
}
c->next = p->next;
} else {
c = c->next;
p = p->next;
}
}
}

Java

updated at 2016/09/23

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode c = newHead, p = c.next;

while (c.next != null && c.next.next != null) {
if (c.next.val == c.next.next.val) {
p = p.next;   // 标记要跳过的节点
while (p.next != null && p.val == p.next.val) {
p = p.next;  // 继续循环标记要删除的节点
}
c.next = p.next;
} else {
c = c.next;
p = p.next;
}
}
}