For somereason this method fails to reverse the linked list

For somereason, this method fails to reverse the linked list. Need a help to figure out a problem.

//does not work even though I tried to return p or u, seems like there are errors in the method

constructor for node is

public class Node {

       public int val;

       public Node next;

       Node(int v){ val=v; }

No de iReverse(Node u Node null Node g u; Node r null whileCa! null q.next; q next p; u p Node reverse Node node) f Node prev null Node current node Node next null while (current null) 1 next current. next current. next J preV prev current current next node preV return node return p; iReverse

Solution

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}

public void add(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.format(\"%d \", temp.value);
temp = temp.next;
}
System.out.println();
}
public static Node iReverse(Node u){
Node p = null;
Node q = u;
Node r = null;
while(q != null){
r = q.next;
q.next = p;
p = q;
q = r;
}
return p;
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node head=new Node(1);
list.add(head);
list.add(new Node(5));
list.add(new Node(3));
list.add(new Node(4));
list.add(new Node(2));

list.printList(head);
//Reversing LinkedList
Node reverseHead=iReverse(head);
System.out.println(\"Reversing:\");
list.printList(reverseHead);

}

}
/*
sample output
1 5 3 4 2
After reversing
2 4 3 5 1
*/

For somereason, this method fails to reverse the linked list. Need a help to figure out a problem. //does not work even though I tried to return p or u, seems l
For somereason, this method fails to reverse the linked list. Need a help to figure out a problem. //does not work even though I tried to return p or u, seems l

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site