2017-04-12 28 views
0

我正在處理「合併兩個排序鏈表」,但它看起來我的頭還沒有被正確更新。合併兩個排序列表,但我的頭沒有更新 - Java

爲了解決這個問題,我嘗試了.val,但它在while循環中無法正常工作。

然後,有線的事情是,當我嘗試.next,它的作品。我完全困惑。 我把這兩個代碼放在下面(工作的和錯誤的),所以你將能夠看到我做了什麼。

有人能給我一個解釋爲什麼第一個不工作,請嗎?

錯誤之一:

/** 
* Definition for ListNode. 
* public class ListNode { 
*  int val; 
*  ListNode next; 
*  ListNode(int val) { 
*   this.val = val; 
*   this.next = null; 
*  } 
* } 
*/ 
public class Solution { 
/** 
* @param ListNode l1 is the head of the linked list 
* @param ListNode l2 is the head of the linked list 
* @return: ListNode head of linked list 
*/ 
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 
    if (l1 == null) 
     return l2; 
    else if (l2 == null) 
     return l1; 

    ListNode result = new ListNode(5); 
    ListNode head = result; 

    while (l1 != null && l2 != null){ 
     if (l1.val < l2.val){ 
      result = l1; 
      l1 = l1.next; 
     } 
     else{ 
      result = l2; 
      l2 = l2.next; 
     } 
     result = result.next; 
    } 

    if (l1 == null){ 
     result = l2; 
    } 
    else{ 
     result = l1; 
    } 

    return head; 

    } 
} 

工作之一:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 
    if (l1 == null) 
     return l2; 
    else if (l2 == null) 
     return l1; 

    ListNode result = new ListNode(5); 
    ListNode head = result; 

    while (l1 != null && l2 != null){ 
     if (l1.val < l2.val){ 
      result.next = l1; 
      l1 = l1.next; 
     } 
     else{ 
      result.next = l2; 
      l2 = l2.next; 
     } 
     result = result.next; 
    } 

    if (l1 == null){ 
     result.next = l2; 
    } 
    else{ 
     result.next = l1; 
    } 

    return head.next; 

} 

唯一的區別是,我在第二個加。接下來。

謝謝!

回答

1

該代碼使用虛擬節點,因此合併後,dummy_node.next將最終指向合併列表。這簡化了代碼,因此它不必有條件地處理最初空的合併列表。 (在C或C++中,可以使用指向節點的指針來代替虛擬節點,但是java沒有等價的代碼)。代碼首先將結果和頭都設置爲虛擬節點的引用,然後前進結果是列表被合併。工作代碼正在返回head.next,這是原來的dummy_node.next。非工作代碼是返回頭,這是對虛擬節點的引用,而不是對合並列表的引用。