In: Computer Science
Can you fix to me this code plz
I just want to print this method as the reverse. the problem is not printing reverse.
public void printBackward() {
Node curr = head;
Node prev = null;
Node next = null;
System.out.print("\nthe backward of
the linkedlist is: ");
while(curr != null) {
next =
curr.next;
curr.next =
prev;
prev =
curr;
curr =
next;
System.out.print(" " + prev.data);
}
public void printBackward(Node head) {
Node curr = head;
Node prev = null;
Node next = null;
System.out.print("\nthe backward of
the linkedlist is: ");
while(curr != null) {
next =
curr.next;
curr.next =
prev;
prev =
curr;
curr = next;
}
node =
prev;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
// I fixed your code please check , if any doubt please comment
// give full program below
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
public void printBackward(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20); // list
85->15->4->20
list.printBackward(head);
}
}