Write a recursive JAVA function named “displayfromend()” which displays thecontents of the linked list from the end in a Doubly Linkedlist
Question
Write a recursive JAVA function named “displayfromend()” which displays thecontents of the linked list from the end in a Doubly Linkedlist
Solution
Here is a simple recursive Java function named "displayFromEnd()" which displays the contents of a doubly linked list from the end:
class Node {
int data;
Node next;
Node prev;
}
class DoublyLinkedList {
Node head;
void displayFromEnd(Node node) {
if (node == null) {
return;
}
displayFromEnd(node.next);
System.out.print(node.data + " ");
}
}
In this code, we first define the structure of a Node in the doubly linked list. Each Node contains an integer data and pointers to the next and previous nodes.
Then, we define the DoublyLinkedList class which has a head Node.
The displayFromEnd() function is a recursive function that starts from the head of the list and goes to the end of the list by recursively calling displayFromEnd() for the next node. When it reaches the end (i.e., when node is null), it starts printing the data of the nodes from the end to the beginning. This is because the print statement is after the recursive call, so it gets executed when the recursive calls start returning.
Similar Questions
Write a JAVA function to find maximum element from doubly linked list
In a doubly linked list, what are possible directions to traverse it?
Q1. How to implement circular linked list in Java ?
import java.util.*;public class linked_list { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<String>(); ll.add("Mercedes"); ll.add("Audi"); ll.add("BMW"); Iterator i = ll.descendingIterator(); while (i.hasNext()) { System.out.println(i.next()); } }}Select one:a.BMWAudiMercedesb.MercedesAudiBMWc.AudiMercedesBMWd.MercedesBMWAudi
What is the output of the following program:import java.util.*;public class linked_list { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<String>(); ll.add("Mercedes"); ll.add("Audi"); ll.add("BMW"); Iterator i = ll.descendingIterator(); while (i.hasNext()) { System.out.println(i.next()); } }}Select one:a.BMWAudiMercedesb.AudiMercedesBMWc.MercedesBMWAudid.MercedesAudiBMW
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.