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).