2017-02-28 26 views
2

我想解決一個簡單的leetcode問題:在我的代碼中反轉鏈接列表有什麼問題?

反轉一個單獨的鏈表。 link

這裏是我的代碼:

/** 
* Definition for singly-linked list. 
* public class ListNode { 
*  int val; 
*  ListNode next; 
*  ListNode(int x) { val = x; } 
* } 
*/ 
public class Solution { 
    public ListNode reverseList(ListNode head) { 
     if (head == null) 
     { 
      return head; 
     } 
     ListNode prev = null; 
     while (head != null && head.next != null) 
     { 
      ListNode current = head; 
      current.next = prev; 
      prev = head; // I think the problem is with this statement 
      head = head.next; 
     } 
     return head; 
    } 
} 

我所試圖做的是通過保存先前的節點在該列表中的所有節點,並在每一步當前節點鏈接到前一個節點迭代ListNode變量。

這裏是測試用例和輸出使事情變得更容易。

輸入:[1,2]輸出:[]預期:[2,1]

同樣,我並不真正需要的一個替代解決方案或者遞歸溶液。我只想知道我的代碼有什麼問題(如果適用的話,還有邏輯)。

回答

3

你的代碼實際上只做一個迭代,因爲它的工作原理如下:

ListNode current = head; 
// You assign head.next to prev here 
// which is equal to null for the first iteration 
current.next = prev; 
prev = head; 
// And here you go to head.next, which was set to null above 
head = head.next; 
// The head is null, so the while loop ends 

當你沒有要求一個正確的解決方案,我只是給出提示如何解決它:你應該在將其分配給prev之前,在某處存儲head.next

2

在覆蓋之前忘了保存head.next。

當您將頭指定給ListNode current時,您只分配一個引用,而不復制節點。因此currenthead(和冗餘)完全同義。