給定一個有序鏈接列表,刪除所有具有重複號碼的節點,只保留原始列表中不同的數字。從已排序的鏈接列表中刪除重複的節點。爲什麼我的輸出錯誤?
例子:
鑑於
1->2->3->3->4->4->5->null
,返回1->2->5->null
。鑑於
1->1->1->2->3->null
,返回2->3->null
。
問題:
- 鑑於
1->1->1->2->3->null
,下面return 3->null
我的解決方案誰能告訴我爲什麼?
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head == null || head.next == null) return head;
ListNode post = head.next;
ListNode curr = head;
ListNode dummy = new ListNode(head.val-1); // make sure dummy node value is different from the head
dummy.next = head;
ListNode prev = dummy;
while(post != null) {
//System.out.println("prev.val = " + prev.val + ", curr.val = " + curr.val + ", post.val = " + post.val + ", prev.next.val = " + prev.next.val);
//System.out.println("prev.next.val = " + prev.next.val + ", curr.next.val = " + curr.next.val);
if(prev.next.val == curr.val && prev.next.val == post.val) {
curr = curr.next;
post = post.next;
}
else if(prev.next.val == curr.val && prev.next.val != post.val) {
curr = curr.next;
post = post.next;
prev.next = curr;
}
else {
prev = prev.next;
curr = curr.next;
post = post.next;
}
}
return dummy.next;
}
}
嘗試返回頭 –
@NicolasFilotto,該類是在頂部 – drdot
@aimee的評論,返回0-> 1-> 1-> 2- > 3-> null – drdot