JAVA QUESTION: A singly linked list method that will:
-A method that will find the largest number in the list
-A method that will find the smallest number in the list
THESE ARE TWO SEPARATE BASIC METHODS
CODE: The above two methods are highlighted in my code.
import java.io.*;
import java.util.*;
public class LinkedList {
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public Node head = null;
public void insert(int data)
{
Node new_node = new Node(data);
new_node.next = null;
if (head == null) {
head = new_node;
}
else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
}
public void print() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of singly linked list: ");
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public void Largest() {
Node curr = head;
// Declaring a max variable and initializing
// it with INT_MIN value.
int max=Integer.MIN_VALUE;
if(head == null) {
System.out.println("List is empty");
}
else {
max = head.data;
while(curr != null){
// If max is less then curr->data then
// assign value of curr->data to max
// otherwise node point to next node.
if(max < curr.data) {
max = curr.data;
}
curr = curr.next;
}
System.out.println("Largest value node in the list: "+ max);
}
}
public void Smallest() {
Node curr = head;
// Declaring a min variable and initializing
// it with INT_MAX value.
int min=Integer.MAX_VALUE;
if(head == null) {
System.out.println("List is empty");
}
else {
min = head.data;
while(curr != null){
// If min is greater then curr->data then
// assign value of curr->data to min
// otherwise node point to next node.
if(min > curr.data) {
min = curr.data;
}
curr= curr.next;
}
System.out.println("Smallest value node in the list: "+ min);
}
}
public static void main(String[] args) {
LinkedList sLL = new LinkedList();
sLL.insert(11);
sLL.insert(2);
sLL.insert(38);
sLL.insert(0);
sLL.insert(76);
sLL.insert(22);
sLL.Largest();
sLL.Smallest();
sLL.print();
}
}
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.