The prev.next.val is working fine inside the while loop but if I print the same outside it gives error. I am not able to understand it why? But if I print the prev.next.val outside the while loop with the if condition, it works and prints the correct value.This is the error I am getting again and again
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode prev=null;
while(head!=null){
dummy=head.next;
head.next=prev;
prev=head;
head=dummy;
if(prev.next!=null){
System.out.println("$"+prev.val); //This works
System.out.println("*"+prev.next.val); //This works
}
}
System.out.println(prev.val); //This works
if(prev.next!=null) System.out.println(prev.next.val); //Also this works. God knows why.
System.out.println(prev.next.val); //This doesn't work
For eg take this TC->1,2,3,4,5. Inside the loop it prints $5 and *4. Outside the loop it prints $5 and *4 too(in the if condition). This means prev.next is not null. But it gives runtime error for prev.next.val after that. Can someone please help? Is there any concept that I am missing out. I am stuck on this since 2 days.
Vishal Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
- We need three pointers,
prev
,head
, andnext
and these four statements to reverse the linked list:
next = head.next; // We save the next node
head.next = prev; // We set the head.next to `prev` node, to change the direction of its pointer.
prev = head; // We update the prev node.
head = next; // We update the current or head node to the next node.
prev
is the previous node.head
is the current node.next
is the next node.
- Finally, we return the
prev
node, which is the last node in the original list, therefore the head of the reversed list.
Code:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public final class Solution {
public static final ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode next;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
ListNode rev = reverseList(head);
while (rev != null) {
System.out.print(rev.val + "t");
rev = rev.next;
}
}
}
Prints
4 3 2 1
Note
- Since we have three pointers, we no longer need a
dummy
node. Theprev
node acts as thedummy
node.