问题
I was doing this leetcode problem and I don't understand why this solution doesn't work. It seems to only be returning the head element. Thanks
/**
* 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;
}
}
回答1:
Read about reference and object in java little bit. Java always passes copy of reference. So when you do,
curr = head;
curr and head point to same object. And when you do,
curr.next = lst;
Both curr.next as well as head.next both starts pointing to null (as lst in null). And you loop breaks next time.
Try this solution it will work.
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;
}
}
回答2:
The other answers have done a good job explaining the problem. To fix the problem, I think all you need in your loop is this:
lst = curr;
curr = head;
head = head.next;
curr.next = lst;
This will traverse the list and reverse the pointers.
Is that what you're looking for?
So the full code:
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;
}
}
回答3:
I think this is because when you set curr = head;, you are setting curr as a reference to head. So when you set head = head.next it is setting head to null and ending the loop.
回答4:
curr = head;
The above line stores reference of head object in curr variable.
curr.next = lst;
Now this makes head.next = null as the lst is initially null and curr is holding the reference of head object.
lst = curr;
You are making variable lst to reference curr which is actually head.
head = head.next;
Now as explained earlier head.next is null so the loop terminates. curr is pointing to head. You have modified the original list which is containing just head of the original list.
来源:https://stackoverflow.com/questions/44077829/reverse-linked-list-java-memory