I was implementing the "reverse single linked list, do it in-place" task. I came up with this solution:
/**
* 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 null;
}
if(head.next==null) return head;
ListNode n = head;
ListNode r = null;
ListNode temp = null;
while (n != null) {
temp = n;
n = n.next;
temp.next = r;
r = temp;
}
return r;
}
}
and it works:
1 2 3 4 5
5 4 3 2 1
but when I wanted to make sure it's the right approach all the solutions I've seen online look like that Reverse single linked list so I started questioning myself... What is wrong with my solution? Time complexity looks like O(n) space com. O(1)... Am I wrong? Thanks in advance!