2
votes

I am trying to solve an easy leetcode problem:

Reverse a singly linked list. link

Here is my code :

/**
 * 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;
    }
}

What I am trying to do is iterate through all nodes of the list and at each step link the current node to the previous node by saving the previous node in a ListNode variable.

Here is the test case and the output to make things easier for you.

Input: [1,2] Output: [] Expected: [2,1]

Again, I am not really looking for an alternate solution or a recursive solution. I just want to know what is wrong with my code(and logic if applicable).

2

2 Answers

3
votes

Your code actually does only one iteration because it works as follows:

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

As you didn't ask for a correct solution, I'll just give a hint how to fix it: you should store head.next somewhere before your assign it to prev.

2
votes

You forgot to save head.next before overwriting it.

When you assign head to ListNode current, you are only assigning a reference, not copying the node. So current is completely synonymous with head (and redundant).