Reverse Linked List

Joined
Jun 7, 2023
Messages
1
Reaction score
0
please find what I'am doing wrong in this code.
3 5 7 9 null is my Linked List
output using this code 3 null
public Node reverseNode(Node head){
Node prevNode = null ;
Node currNode = head ;
Node tempNode = currNode ;
while (currNode != null) {
currNode.next = prevNode ;
prevNode = currNode ;
currNode = tempNode.next ;
tempNode = currNode ;
}
head = prevNode;
return head ;
}
 
Joined
Sep 21, 2022
Messages
121
Reaction score
15
This is a guess, since I've read only one Java book, and have written zero Java programs.

Before the while loop, tempNode and currNode have the same value. They are references to the same node.

so, inside the loop,

currNode.next = prevNode;

is also changing the value of tempNode.next

Which is a problem.
 
Joined
Sep 21, 2022
Messages
121
Reaction score
15
Perhaps I should clarify,

tempNode = currNode ;

does not copy the node, tempNode now refers to the same node as currNode.

To get the program to work,

tempNext = currNode.next;

would be a better approach.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,757
Messages
2,569,543
Members
45,026
Latest member
camilin05

Latest Threads

Top