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