Question

In: Computer Science

Complete the following methods: secondlargest(): returns the second largest in the list without sorting. Assumes list...

Complete the following methods:
secondlargest(): returns the second largest in the list without sorting. Assumes list
has at least 2 elements.
palindrome(): checks if list elements are palindrome, i.e. list elements from left to
right and right to left, are identical.


Code:

import java.util.*;
import java.io.*;

public class xxxxxL1 {
   // class Variables
    private int n, count, arr[];
   PrintStream prt = System.out;
   // xxxxxL1 Constructor
   xxxxxL1(int k){
      count = 0;
      n = k;
      //   Allocate Space for array         
      arr = new int[n+1];// index 0 is not used
      prt.printf("\tCreating array of size %2d:",n);
   } // end constructor
  
   //prints list formatted 10 elements per line.
   private void printlist(){
      int i;
      prt.print("\n\tList contents:\n\t");
      for (i = 1; i <= count; i++){
       prt.printf("%2d, ", arr[i]);
       if (i % 10 == 0) prt.printf("\n\t");
      }
    } // end printlist  
  
   // Return second largest in the list.
   // Assume list has 2 or more elements.
    private int secondlargest(){
       return 0;
    } // end secondlargest
      
    // deletes x from list, if exist.
    private int delete(int x){
      int i, j;
      if (count == 0)
           return 0; // invalid position
   //shift array elements from position p to right
      for (i = 1 ; i <= count ; i++)
       if (arr[i] == x){
       for (j = i ; j < count ; j++)
             arr[j] = arr[j+1];
       count--;
       return 1;
       }
      return 1;
    } //end delete

   //checks if list elements are palindrome, i.e.
   //list elements from left to right and right to
   //left, are identical.
    private int palindrome(){
       return 0;
    } // end palindrome

   //insert x at position p, in list
   //for successful insertion: list should not be
   // full(count=n) and 1 <= p <= count+1
    private int insert(int x, int p){
      int i;
      if (count == n || p < 1 || p > count+1)
           return 0; // invalid position
   //shift array elements from position p to right
      for (i = count ; i >= p ; i--)
       arr[i+1] = arr[i];
      // end for
              
      arr[p] = x; // insert x at position p
      count++; // increment no. of elements.
      return 1; // successful insertion
   } // end insert


   public static void main(String args[]) throws Exception{
      int j, m, k, p, s, x;
      try{
       // open input file
       Scanner inf = new Scanner(System.in);
        // read list size      
       k = inf.nextInt();
       // Create a List of type Integer of size k
       xxxxxL1 lst = new xxxxxL1(k);          

       //read no. of elements to insert
       m = inf.nextInt();
       //Insert m elements in the list
        for(j = 1; j <= m; j++){
           x = inf.nextInt();   // read x
           p = inf.nextInt(); // read position
          //insert x at position p
          s = lst.insert(x, p);
           //if (s == 1)System.out.printf(" Successful insertion.");  
           //else               System.out.printf(" Can not insert.");
         } // end for
      
       //prints list formatted 10 elements per line.
       lst.printlist();

       //print second largest
       //p = lst.secondlargest();
         //System.out.printf("\n\t2nd largest = %d.", p);

        //read no. of elements to delete from list
        k = inf.nextInt();
       //Delete k elements from the lis
        for(j = 1; j <= k; j++){
           x = inf.nextInt();   // read next int
           p = lst.delete(x);   //delete x
           //if (p ==1) System.out.printf(": deleted.");
           //else System.out.printf(": not found.");
        }// end for

       //prints list formatted 10 elements per line.
       lst.printlist();
      
       // close input file       
       inf.close();
       } catch (Exception e) {
        System.out.print("\nException " + e + "\n");}
    } // end main
   } // end class xxxxxL1

Solutions

Expert Solution

I have made a program to find 2nd largest and check if it is palindrome. It acts on a list. Please incorporate the same in your code.

2nd Largest


 private int secondlargest() {
     int largest = 0, secondLargest = 0;
     for (int i = 0; i < arr.length; i++) {
         if (i == 0) {
             largest = arr[i]; // initially consider 1st element as largest
         } else {
             if (largest < arr[i]) {       // if 2nd element is larger than 1st, secondLargest becomes the previous largest and currect largest is the ith element
                 secondLargest = largest;
                 largest = arr[i];
             } else {                      
                 if (secondLargest < arr[i]) {      // if ith element is lesser than largest, we compare the secondLargest element with ith element and change secondLargest to ith element if ith element is greater
                     secondLargest = arr[i];
                 }
             }
         }
     }
     return secondLargest;   //last value of secondLargesr after we are done with traversing is 2nd largest value of list
 }


INPUT/OUTPUT

arr = {1 , 2 , 3 , 5}
secondLargest is 3


Palindrome -> As it checks, the return type I have changed to boolean. You can use int also. 1 for palindrome and 0 for not palindrome.

  private boolean palindrome() {
      int length = arr.length;
      if (length % 2 == 0) {
          //if length is even
          for (int i = 0; i < (length) / 2; i++) { // if length is odd, we compare first and last. 2nd and 2nd last. 3rd and 3rd last and so on..... The middle element is NOT common while traversing from both sides. SO, comparing first half and 2nd half.
              if (arr[i] != arr[length - 1 - i]) {
                  return false;
              }
          }
      } else {
          //if length is odd
          for (int i = 0; i < (length - 1) / 2; i++) { // if length is odd, we compare first and last. 2nd and 2nd last. 3rd and 3rd last and so on..... The middle element is common while traversing from both sides
              if (arr[i] != arr[length - 1 - i]) {
                  return false;
              }
          }

      }
      return true;
  }


INPUT/OUTPUT

arr = {1 , 2 , 3 , 0 , 0 , 3 , 2 , 1} -> TRUE
arr = { 1 , 2 , 3 , 2 , 1} -> TRUE
arr={1 ,2 ,3 ,1 , 2} -> FALSE







Kindly upvote if this helped


Related Solutions

SML Complete the following programs. 1. Write a function listify that takes a list and returns...
SML Complete the following programs. 1. Write a function listify that takes a list and returns a list of lists where each element of first list becoming its own single-element list (Fill in the code here) fun main() = let val lst = (explode "rad"); in print (PolyML.makestring ( listify lst )) end; 2. Write a function splitlist that takes a list of pairs and returns a pair of lists that has the firsts of the pairs in one list...
Use the list of transactions on the following page to complete the following: Complete the Horizontal...
Use the list of transactions on the following page to complete the following: Complete the Horizontal Balance Sheet (excel file available in Canvas) by recording all activity reported by your client (following page). Using the completed Horizontal Balance Sheet, create an Income Statement & Vertical Balance Sheet by using the template provided in the excel file (in Canvas). Create a flexible budget that shows expected revenues and expenses at three different volumes of ice cream bars sold (using the excel...
Complete the following methods in java: Consult the rest of the methods of BigInteger from its...
Complete the following methods in java: Consult the rest of the methods of BigInteger from its API documentation as needed to solve the following problems. public static List<BigInteger> fibonacciSum(BigInteger n) The unique breakdown into Fibonacci numbers can be constructed with a greedy algorithm that simply finds the largest Fibonacci number f that is less than or equal to n. Add this f to the result list, and break down the rest of the number given by the expression n-f the...
In Java: Complete the following methods in the template by adhering to the comments: // TO...
In Java: Complete the following methods in the template by adhering to the comments: // TO DO: add your implementation and JavaDoc public class BetterArray<T> { private static final int DEFAULT_CAPACITY = 2; //default initial capacity / minimum capacity private T[] data; //underlying array, you MUST use this for full credit // ADD MORE PRIVATE MEMBERS HERE IF NEEDED! @SuppressWarnings("unchecked") public BetterArray() { //constructor //initial capacity of the array should be DEFAULT_CAPACITY } @SuppressWarnings("unchecked") public BetterArray(int initialCapacity) { // constructor...
For this question you will need to use the following library function: Math.floor(x) returns the largest...
For this question you will need to use the following library function: Math.floor(x) returns the largest whole number less than or equal to x Define a function named weight which has one input. The input is a Number representing a person's weight in pounds. Your function will calculate and return a string saying how much they weigh in stone. Your function should start by multiplying the input by 0.0714286. Because stone weight is always a whole number, your function will...
Refer to the scenario to answer the following question(s): Unilever, the world’s second largest consumer goods...
Refer to the scenario to answer the following question(s): Unilever, the world’s second largest consumer goods company, received a jolt in 2004 when its stock price fell sharply after management had warned investors that profits would be lower than anticipated. Even though the company had been the first consumer goods company to enter the world’s emerging economies in Africa, China, India, and Latin America with a formidable range of products and local knowledge, its sales faltered when rivals began to...
Question 3, and 4 2.(50 pts) For the following list of nuclides, complete the following: List...
Question 3, and 4 2.(50 pts) For the following list of nuclides, complete the following: List the number of protons Hydrogen-1= 1 Iron-56 =26 Zirconium-91= 40 Gold-197 =79 Uranium-238: 92 List the number of neutrons Hydrogen-1 = 0 Iron-56 = 30 Zirconium-91 = 51 Gold-197 = 118 Uranium-238: 146 Write out the nuclide in the form   Hydrogen-1 = 1 H 1 Iron-56 = 56 Fe 26 Zirconium-91 = 91 Zr 40 Gold-197 = 197 Au 79 Uranium-238 = 238 U...
Which of the following methods displays the second form on top of the main form? Group...
Which of the following methods displays the second form on top of the main form? Group of answer choices PresentForm() ShowDialog() DisplayForm() ShowForm() - Which of the following statements closes the form: Group of answer choices Close().Me Close().Form Me.Close() Form.Close() -To create an instance of a form, using the following statement. what the ? (question mark) must be? Dim frmForm1 As ? Form1 Group of answer choices DESIGN NEW GENERATE CREATE Where do you type the code for menu? Group...
Please complete following c++ code asap using following prototypes complete each missing part / Linked list...
Please complete following c++ code asap using following prototypes complete each missing part / Linked list operations int getLength() const {return length;} void insertNode(College); bool deleteNode(string); void displayList() const; bool searchList(string, College &) const; }; main.cpp /*   Build and procees a sorted linked list of College objects. The list is sorted in ascending order by the college code. Assume that the college code is unique. */ #include <iostream> #include <fstream> #include <string> #include "LinkedList.h" using namespace std; void buildList(const string...
package labs; Complete the following code /* * Purpose: Look at LinkedList, overloaded methods and *...
package labs; Complete the following code /* * Purpose: Look at LinkedList, overloaded methods and * write a simple method to check if the LinkedList actually contains any loops/cycles in it. */ public class LinkedList<E> { private static class Node<E> { E data; Node<E> next; public Node(E d) { data=d; next=null; } } private Node<E> head; private Node<E> tail; /* * data of type E, first gets put into a Node * and then the Node gets added onto the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT