Using the template below write a program that reverses a LinkedList in java /***
ID: 3749236 • Letter: U
Question
Using the template below write a program that reverses a LinkedList in java
/*******************
Name:
Date:
Notes:
*******************/
// Java program for reversing the linked list
class MyLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
Node reverse(Node node) {
add content
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
add content }
}
Explanation / Answer
/******************* Name: Date: Notes: *******************/ // Java program for reversing the linked list class MyLinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverseHelper(Node node) { if(node.next == null) { return node; } else { Node temp = reverseHelper(node.next); node.next.next = node; return temp; } } Node reverse(Node node) { Node newHead = reverseHelper(node); node.next = null; return newHead; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { MyLinkedList list = new MyLinkedList(); head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = null; System.out.print("Normal list: "); list.printList(head); head = list.reverse(head); System.out.print(" Reversed list: "); list.printList(head); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.