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
.
SOLUTION 1:
使用一个del标记来删除最后一个重复的字元。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
} // record the head.
ListNode dummy = new ListNode(0);
dummy.next = head; ListNode cur = dummy; // to delete the last node in the list of duplications.
boolean del = false; while (cur != null) {
if (cur.next != null
&& cur.next.next != null
&& cur.next.val == cur.next.next.val) {
cur.next = cur.next.next;
del = true;
} else {
if (del) {
cur.next = cur.next.next;
del = false;
} else {
cur = cur.next;
}
}
} return dummy.next;
}
}
SOLUTION 2:
使用一个pre, 一个cur来扫描,遇到重复的时候,使用for循环用cur跳过所有重复的元素。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
} ListNode dummy = new ListNode(0);
dummy.next = head; ListNode pre = dummy;
ListNode cur = pre.next; while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
while (cur != null && cur.val == pre.next.val) {
cur = cur.next;
} // delete all the duplication.
pre.next = cur;
} else {
cur = cur.next;
pre = pre.next;
}
} return dummy.next;
}
}