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.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
方法一:先找到重复的那个数,把和他一样的后面的数全去掉
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while(head.next != null && head.next.next != null) {
if(head.next.val == head.next.next.val) {
int val = head.next.val;
while(head.next != null && head.next.val == val) {
head.next = head.next.next;
}
}else head = head.next;
}
return dummy.next;
}
}
方法二:三个指针,real指针在对的情况下才前进(数字与前与后都不同)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
ListNode real, pre, cur;
real = dummy;
pre = real;
cur = head;
while(cur != null) {
if((pre == dummy || pre.val != cur.val) && (cur.next == null || cur.val != cur.next.val)) {
real.next = cur;
real = cur;
}
pre = cur;
cur = cur.next;
pre.next = null;
}
return dummy.next;
}
}