Question: Reverse a Doubly Linked List Given a doubly linked list, complete the public void reverseList( ) method that will reverse the elements in the list.
Reverse a Doubly Linked List Given a doubly linked list, complete the public void reverseList( ) method that will reverse the elements in the list. Make sure your program addresses edge cases such as an empty list.
Sample Input: 10 20 30 -1
Sample Output: Content of the doubly linked list: 10 20 30 Content of the list after reversal: 30 20 10
Explanation: Three elements are the input to the list and the end of input marker is -1. The program prints the contents of the list before and after calling the method reverseList( )
import java.util.Scanner;
public class DoublyLinkedList { Node head; public static void main(String[] args){ DoublyLinkedList dList = new DoublyLinkedList(); Scanner input = new Scanner(System.in); while(true){ int data = input.nextInt(); if(data == -1) break; dList.append(data); } System.out.println("Content of the doubly linked list:"); dList.print(); dList.reverseList(); System.out.println(" Content of the list after reversal:"); dList.print();
}
public void append(int data){ Node newNode = new Node(data); if(head == null){ head = newNode;
} else{ Node currentNode = head; while(currentNode.next != null){ currentNode = currentNode.next; } currentNode.next = newNode; newNode.prev = currentNode; } }
public void print(){ if(head == null){ System.out.print("Empty list."); return; } Node currentNode = head; while(currentNode != null){ System.out.print(currentNode.data + " "); currentNode = currentNode.next; } } // Reverse the list public void reverseList(){ } }
______Node class
public class Node{ int data; Node next; Node prev; public Node(int data){ this.data = data; next = prev = null; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
