Question

In: Computer Science

This is a Java program that I am having trouble making. 1- Search for the max...

This is a Java program that I am having trouble making.

1- Search for the max value in the linked list.

2- Search for the min value in the linked list.

3- Swap the node that has the min data value with the max one. (Note: Move the nodes to the new positions).

4- Add the min value and the max value and insert the new node with the calculated value before the last node.

I already made a generic program that creates the linked list and has the ability to add and remove from the list. I am not sure how to create these generic methods though.

Below is my attempt to make the min finder, but it does not work and gives me an error on the bolded parts. It says "bad operand types for binary operator >".

LList.java below:


package llist;

/**
*
* @author RH
* @param <E>
*/
public class LList<E> {

Node head, tail;
int size;

public LList() {
size = 0;
head = tail = null;
}

public void addFirst(E element) {
Node newNode = new Node(element);
newNode.next = head;
head = newNode;
size++;
if (tail == null) {
tail = head;
}
}

public void addLast(E element) {
Node newNode = new Node(element);

if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
size++;
}

public void insert(int index, E element) {

if (index == 0) {
addFirst(element);
} else if (index >= size) {
addLast(element);
} else {
Node current = head;

for (int i = 1; i < index; i++) {
current = current.next;
}

Node holder = current.next;
current.next = new Node(element);
current.next.next = holder;
size++;
}
}

public void remove(int e) {
if (e < 0 || e >= size) {
System.out.println("Out of bounds");
} else if (e == 0) {
System.out.println("Deleted " + head.element);
head = head.next;
size--;
} else if (e == size - 1) {
Node current = head;
Node holder;
for (int i = 1; i < size; i++) {
current = current.next;
}
System.out.println("Deleted " + current.element);
tail.next = current.next;

tail = tail.next;
size--;
} else {
Node<E> previous = head;
for (int i = 1; i < e; i++) {
previous = previous.next;
}

System.out.println("Deleted " + previous.next.element);

Node<E> current = previous.next;
previous.next = current.next;
size--;
}
}

public int largestElement() {

int max = 49;

while (head != null) {

if (max < head.next) {
max = head.next;
}
head = head.next;
}
return max;
}

public int smallestElement() {

int min = 1001;

while (head != null) {

if (min > head.next) {
min = head.next;
}

head = head.next;
}
return min;
}

public void print() {
Node current = head;

for (int i = 0; i < size; i++) {
System.out.println(current.element);
current = current.next;
}
}
}

Node.java below:

package llist;

/**
*
* @author RH
* @param <E>
*/
public class Node<E> {

E element;
Node next;
  
public Node(E data) {
this.element = data;
}   
}

Driver.java below:

package llist;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* @author RH
*/
public class Driver {
public static void main(String[] args) {
LList<Integer> listy = new LList();
  
// adds 10 random numbers to the linkedlist
for (int i = 0; i < 10; i++) {
listy.addFirst(ThreadLocalRandom.current().nextInt(50, 1000 + 1));
}
  
  
System.out.println("");
  
listy.print();
  
System.out.println("");
  
int max = listy.largestElement();
  
int min = listy.smallestElement();
  
System.out.println(max);
  
System.out.println(min);
//listy.remove(1);
  
//System.out.println("");
  
//listy.print();
}
  
}

I am not sure how to get these generic methods made.

Solutions

Expert Solution

/* I HAVE CORRECTED YOUR ADDFIRST METHOD ALSO ADDED REMAINING METHODS THAT NEED TO BE IMPLEMENTED COPY AND PASTE YOUR CODE ADD YOUR PACKAGE NAME YOURSELF*/

/* Node.java */

public class Node<E> {

E element;
Node next;

public Node(E data) {
this.element = data;
this.next = null;
}

}

/*LList.java */

public class LList<E> {

Node head, tail;
int size;

public LList() {
size = 0;
head = tail = null;
}

public void addFirst(E element) {
Node newNode = new Node(element);
size++;
if(tail == null && head == null){
tail = head = newNode;
}else{
newNode.next = head;
head = newNode;

}
}

public void addLast(E element) {
Node newNode = new Node(element);

if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
size++;
}

public void insert(int index, E element) {

if (index == 0) {
addFirst(element);
} else if (index >= size) {
addLast(element);
} else {
Node current = head;

for (int i = 1; i < index; i++) {
current = current.next;
}

Node holder = current.next;
current.next = new Node(element);
current.next.next = holder;
size++;
}
}

public void remove(int e) {
if (e < 0 || e >= size) {
System.out.println("Out of bounds");
} else if (e == 0) {
System.out.println("Deleted " + head.element);
head = head.next;
size--;
} else if (e == size - 1) {
Node current = head;
Node holder;
for (int i = 1; i < size; i++) {
current = current.next;
}
System.out.println("Deleted " + current.element);
tail.next = current.next;

tail = tail.next;
size--;
} else {
Node<E> previous = head;
for (int i = 1; i < e; i++) {
previous = previous.next;
}

System.out.println("Deleted " + previous.next.element);

Node<E> current = previous.next;
previous.next = current.next;
size--;
}
}

public int largestElement() {

int max = (int)head.element ;
  
Node curr = head;
curr = curr.next;
while (curr != null) {

if (max < (int)curr.element) {
max = (int)curr.element;
}
curr = curr.next;
}
return max;
}

public int smallestElement() {

int min = (int)head.element;
Node curr = head;
curr = curr.next;
while (curr != null) {

if (min > (int)curr.element) {
min = (int)curr.element;
}

curr = curr.next;
}
return min;
}

public void print() {
Node current = head;

for (int i = 0; i < size; i++) {
System.out.println(current.element);
current = current.next;
}
}
public void swapNodes(int x, int y)
{
// Nothing to do if x and y are same
if (x == y) return;
  
// Search for x (keep track of prevX and CurrX)
Node prevX = null, currX = head;
while (currX != null && (int)currX.element != x)
{
prevX = currX;
currX = currX.next;
}
  
// Search for y (keep track of prevY and currY)
Node prevY = null, currY = head;
while (currY != null && (int)currY.element != y)
{
prevY = currY;
currY = currY.next;
}
  
// If either x or y is not present, nothing to do
if (currX == null || currY == null)
return;
  
// If x is not head of linked list
if (prevX != null)
prevX.next = currY;
else //make y the new head
head = currY;
  
// If y is not head of linked list
if (prevY != null)
prevY.next = currX;
else // make x the new head
head = currX;
  
// Swap next pointers
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
}

/* Driver.java */

import java.util.concurrent.ThreadLocalRandom;

public class Driver {
public static void main(String[] args) {
  
LList<Integer> listy = new LList();

// adds 10 random numbers to the linkedlist
for (int i = 0; i < 10; i++) {
listy.addFirst(ThreadLocalRandom.current().nextInt(50, 1000 + 1));
}


System.out.println("");

listy.print();

System.out.println("");

int max = listy.largestElement();

int min = listy.smallestElement();

System.out.println("1. Max: "+max);

System.out.println("2. Min: "+min);
System.out.println("3. Swap Min and Max ");
listy.swapNodes(max, min);
System.out.println("");
listy.print();
  
int sum = min + max;
System.out.println("4. Add sum of min and max at second last");
int index = listy.size-1;
listy.insert(index, sum);
  
System.out.println("");
listy.print();
System.out.println("");
listy.remove(1);
  
System.out.println("");
listy.print();
}
  
}

/* OUTPUT */


Related Solutions

Hello! I am having trouble starting this program in Java. the objective is as follows: "...
Hello! I am having trouble starting this program in Java. the objective is as follows: " I will include a text file with this assignment. It is a text version of this assignment. Write a program that will read the file line by line, and break each line into an array of words using the tokenize method in the String class. Count how many words are in the file and print out that number. " my question is, how do...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am taking a Data Structures and Program Design class. BUT, I am having trouble getting...
I am taking a Data Structures and Program Design class. BUT, I am having trouble getting access to the vectors so that I can compare the guesses with the random numbers. I’ve been working on this for several days and don't feel any closer to a solution and could really use some help as I really don't know how to get this to work. Thank you! The assignment is: Design an ADT for a one-person guessing game that chooses 4...
(Java) Building a Doubly Linked List off of an interface I am having trouble with these...
(Java) Building a Doubly Linked List off of an interface I am having trouble with these two methods @Override public void add(T newEntry) { DoubleLinkedNode newNode = new DoubleLinkedNode(newEntry); if (!isEmpty()) { } if (isEmpty()) { first = newNode; last = newNode; } else { last.setNextNode(newNode); newNode.setPreviousNode(last); last = newNode; } // length++; numElements++; } @Override public void add(int newPosition, T newEntry) { DoubleLinkedNode newAdder = new DoubleLinkedNode(newEntry); if ((newPosition >= 0) && (newPosition <= numElements)) { numElements++; if (newPosition...
I am having trouble with how and determining when making the right decision of Qualitative Factors...
I am having trouble with how and determining when making the right decision of Qualitative Factors and identifying them in under the Types of Incremental Analysis? As it says in the text, "the potential effects of the make-or-buy decision or of the decision to eliminate a line of business on existing employees and the community in which the plant is located. The cost savings that may be obtained from outsourcing or from eliminating a plant should be weighed against these...
I am having the most trouble with 1d: 1. a. Prove that if f : A...
I am having the most trouble with 1d: 1. a. Prove that if f : A → B, g : B → C, and g ◦f : A → C is a 1-to-1 surjection, then f is 1-to-1 and g is a surjection. Proof. b. Prove that if f : A → B, g : B → C, g ◦ f : A → C is a 1-to-1 surjection, and g is 1-to-1, then f is a surjection. Proof. c....
I am having trouble making an income statement, Statement of owner's equity, and Balance sheet out...
I am having trouble making an income statement, Statement of owner's equity, and Balance sheet out of this information Chapter 3 Assignment 10-01-2018 1.00 1.00 0.99 Hide or show questions Progress:3/3 items eBook Calculator Adjusting Entries and Adjusted Trial Balances Reece Financial Services Co., which specializes in appliance repair services, is owned and operated by Joni Reece. Reece Financial Services’ accounting clerk prepared the following unadjusted trial balance at July 31, 2019: Reece Financial Services Co. Unadjusted Trial Balance July...
I was able to calculate (a) but I am having trouble with the calculations of (b)....
I was able to calculate (a) but I am having trouble with the calculations of (b). Thanks! The following are New York closing rates for A$/US$ and $/£:                                     A$/$ = 1.5150;               $/£ = $1.2950             (a) Calculate the cross rate for £ in terms of A$ (A$/£).             (b) If £ is trading at A$1.95/£ in London (cross market) on the same day, is there an arbitrage opportunity?  If so, show how arbitrageurs with £ could profit from this opportunity and calculate the arbitrage...
I am having an issue with the Java program with a tic tac toe. it isn't...
I am having an issue with the Java program with a tic tac toe. it isn't a game. user puts in the array and it prints out this. 1. Write a method print that will take a two dimensional character array as input, and print the content of the array. This two dimensional character array represents a Tic Tac Toe game. 2. Write a main method that creates several arrays and calls the print method. Below is an example of...
I am working through this solution in rstudio and am having trouble fitting this table into...
I am working through this solution in rstudio and am having trouble fitting this table into a linear regression analysis. an answer with corrosponding r code used would be greatly appreciated A study was conducted to determine whether the final grade of a student in an introductory psychology course is linearly related to his or her performance on the verbal ability test administered before college entrance. The verbal scores and final grades for all 1010 students in the class are...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT