Write a JAVA function to find maximum element from doubly linked list
Question
Write a JAVA function to find maximum element from doubly linked list
Solution
Sure, here is a simple Java function to find the maximum element from a doubly linked list:
class Node {
int data;
Node next, prev;
Node(int data) {
this.data = data;
next = prev = null;
}
}
class LinkedList {
Node head;
// Function to find maximum element
int findMax() {
if (head == null)
return Integer.MIN_VALUE;
int max = head.data;
Node current = head;
// Traverse through the list
while (current != null) {
if (current.data > max)
max = current.data;
current = current.next;
}
return max;
}
}
In this code, we first check if the list is empty. If it is, we return the smallest possible integer value as there is no element in the list. If the list is not empty, we initialize the maximum value as the data of the head node. Then we traverse through the list. For each node, we compare its data with the current maximum value. If it's greater, we update the maximum value. Finally, we return the maximum value after the traversal.
Similar Questions
use reduce function to find the maximum element of the list.
Write a recursive JAVA function named “displayfromend()” which displays thecontents of the linked list from the end in a Doubly Linkedlist
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
How is the last node identified in a doubly linked list?
Write a Java function that delete odd nodes from the doubly linked list.
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.