题目:Remove Duplicates from Sorted List II
难度:medium
问题描述:
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
.
解题思路:将重复的节点全部去除。解题技巧是设置一个头结点extra,使得extra.next=head。这样可以在head也被删时灵活表示。最后输出extra.next即可。
具体代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null){
return head;
}
boolean gate=false;
ListNode extra=new ListNode(0);
extra.next=head;
ListNode last=extra,index=head;
while(true){
if(index.next.val==index.val){
index=index.next;
gate=true;
}else{
index=index.next;
if(gate){
last.next=index;
gate=false;
}else{
last=last.next;
}
}
if(index.next==null){
if(gate){
last.next=null;
}
break;
}
}
return extra.next;
}
}