Java for LeetCode 082 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.
解题思路:
用指针即可,JAVA实现如下:
public ListNode deleteDuplicates(ListNode head) {
while (head != null && head.next != null) {
ListNode temp = head.next;
if (temp.val == head.val) {
while (temp.val == head.val) {
temp = temp.next;
if (temp == null)
return null;
}
head = temp;
continue;
} else
break;
}
if (head == null || head.next == null)
return head;
ListNode temp = head.next;
ListNode last = head;
while (temp != null && temp.next != null) {
if (temp.val != temp.next.val) {
last.next = temp;
temp = temp.next;
last=last.next;
continue;
}
int tmp=temp.val;
while(temp.val==tmp){
temp=temp.next;
if (temp == null){
last.next=null;
return head;
}
}
}
last.next=temp;
return head;
}

浙公网安备 33010602011771号