In: Computer Science
Java coding:
2. Write a method which takes a list list of int , and reverse it. // recursion
3.Write a method which takes a list list of strings , and reverse it. // in different way than the previous
3. Write a two methods which take a list and find the largest integer number in it.
2. Java_program for reversing the linked_list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next =
null;
}
}
/* Function to reverse_linked_list */
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next =
current.next;
current.next =
prev;
prev =
current;
current =
next;
}
node = prev;
return node;
}
// prints_content of double_linked_list
void print List(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node =
node.next;
}
}
public static void main(String[] args)
{
LinkedList list = new
LinkedList();
list.head = new Node(65);
list.head.next = new
Node(25);
list.head.next.next = new
Node(14);
list.head.next.next.next = new
Node(20);
System.out.println("Given
Linked_list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed
linked_list ");
list.printList(head);
}
}
Output: Given linked_list 65 25 14 20 Reversed Linked_list 20 14 25 65
3. Take a list of strings , reverse it.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class Main
{
public static void main(String[] args)
{
List<String> colors = new ArrayList<>(
Arrays.asList("GREEN", "YELLOW", "BLACK")); // INITIALIZE THE
LIST
Collections.reverse(colors);
System.out.println(colors);
}
}
output: BLACK YELLOW GREEN
3. find the largest integer number from a list in java
Method_1: Iterative_Way
// Java Program to find largest integer number from a list
class Test
{
static int arr[] = {100, 124, 145, 190, 808};
// Method to find largest integer number from a
list
static int largest()
{
int i;
// Initialize max integer
int max = arr[0];
// Traverse list (array) elements
from second and
// compare every element with
current max
for (i = 1; i < arr.length;
i++)
if (arr[i] >
max)
max = arr[i];
return max;
}
// Driver_method
public static void main(String[] args)
{
System.out.println("Largest in list
is " + largest());
}
}
Output:
Largest in list is 808
Method 2 : Sorting List
// Java Program to find largest integer number from a list
// arr[] of size n
import java .io.*;
import java.util.*;
class GFG
{
// returns maximum number from a list
static int largest(int []arr,
int n)
{
Arrays.sort(arr);
return arr[n - 1];
}
// Driver code
static public void main (String[] args)
{
int []arr = {10, 24, 45,
90, 980};
int n = arr.length;
System.out.println(largest(arr,
n));
}
}
Output: 980