题目链接:
Remove Duplicates from Sorted List II
题目简介:
1-2-3-3-4-4-5 返回 1-2-5
1-1-2-3 返回 2-3
题目解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)
return head;
ListNode pre = null;
ListNode now = head;
ListNode latest_point_holder = null; // asume 100% has value
ListNode realHead = null;
// 1 2 3 3 4 4 5
while(now!=null){
// see pre && next
if(pre!=null){
if(now.val == pre.val){now = now.next;continue;}
}
if(now.next!=null){
if(now.next.val ==now.val){pre=now;now=now.next;continue;}
}
// !=pre && !=next
if(now!=null&&realHead == null){
realHead = now;
latest_point_holder = now;
pre = now;
now=now.next;
}else {
if(now!=null){
latest_point_holder.next = now;
latest_point_holder=now;
pre = now;
now=now.next;
}
}
}
if(latest_point_holder!=null)latest_point_holder.next=null;
return realHead;
}
}
题目耗时:0ms