我正在做这个leetcode问题,我不明白为什么这个解决方案不起作用。它似乎只返回头部元素。谢谢
/**
* 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) {
ListNode curr = null;
ListNode lst = null;
while (head != null)
{
curr = head;
curr.next = lst;
lst = curr;
head = head.next;
}
return curr;
}
}
其他答案在解释问题方面做得很好。 要解决此问题,我认为您在循环中所需要的只是:
lst = curr;
curr = head;
head = head.next;
curr.next = lst;
这将遍历列表并反转指针。
这就是你要找的吗?
所以完整的代码:
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode curr = null;
ListNode lst = null;
while (head != null)
{
lst = curr;
curr = head;
head = head.next;
curr.next = lst;
}
return curr;
}
}
阅读一下 java 中的引用和对象。Java总是传递引用的副本。所以当你这样做时,
curr = head;
curr 和 head 指向同一对象。当你这样做时,
curr.next = lst;
curr.next 和 head.next 都开始指向 null(如 null 中的 lst(。下次你循环休息。
试试这个解决方案它会起作用。
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode nxt = null;
ListNode lst = null;
while (head != null)
{
nxt = head.next;
head.next = lst;
lst = head;
head = nxt;
}
return lst;
}
}
这是因为当您设置curr = head;
时,您将curr
设置为对head
的引用。因此,当您设置head = head.next
时,它将head
设置为 null 并结束循环。
curr = head;
上行将head
对象的引用存储在变量curr
。
curr.next = lst;
现在,这使得head.next
= null
因为lst
最初是null
的,并且curr
持有head
对象的引用。
lst = curr;
您正在制作变量lst
来引用实际上head
curr
。
head = head.next;
现在如前所述head.next
null
,因此循环终止。 curr
指向head
.您已经修改了原始列表,该列表仅包含原始列表的头部。