【发布时间】:2017-02-28 17:28:58
【问题描述】:
我正在尝试解决一个简单的 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]
再一次,我并不是真的在寻找替代解决方案或递归解决方案。我只想知道我的代码有什么问题(如果适用,还有逻辑)。
【问题讨论】:
标签: java algorithm data-structures linked-list