Question

In: Computer Science

JAVA- Modify the LinkedList1 class presented in this chapter by adding sort() and reverse() methods. The...

JAVA-

Modify the LinkedList1 class presented in this chapter by adding sort() and reverse() methods. The reverse method reverses the order of the elements in the list, and the sort method rearranges the elements in the list so they are sorted in alphabetical order. The class should use recursion to implement the sort and reverse operations. Extend the graphical interface in the LinkedList1Demo class to support sort and reverse commands, and use it to test the new methods.

LinkedList1:

class LinkedList1
{
  
private class Node
{
String value;
Node next;
  
  
  
Node(String val, Node n)
{
value = val;
next = n;
}
  
  
  
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
  
private Node first; // list head
private Node last; // last element in list
  
  
public LinkedList1()
{
first = null;
last = null;
}
  
public boolean isEmpty()
{
return first == null;
}
  
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
  
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
  
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
  
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
  
  
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
  
  
pred.next = new Node(e, pred.next);
  
  
if (pred.next.next == null)
last = pred.next;
}
  
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
  
Node p = first;
while (p != null)
{
strBuilder.append(p.value + "\n");
p = p.next;
}
return strBuilder.toString();
}
  
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
  
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element = first.value;
first = first.next;
if (first == null)
last = null;
}
else
{
  
Node pred = first;
  
  
for (int k = 1; k <= index -1; k++)
pred = pred.next;
  
  
element = pred.next.value;
  
  
pred.next = pred.next.next;
  
  
if (pred.next == null)
last = pred;
}
return element;
}
  
public boolean remove(String element)
{
if (isEmpty())
return false;
  
if (element.equals(first.value))
{
  
first = first.next;
if (first == null)
last = null;
return true;
}
  
  
Node pred = first;
while (pred.next != null &&
!pred.next.value.equals(element))
{
pred = pred.next;
}
  
  
if (pred.next == null)
return false;
  
  
pred.next = pred.next.next;
  
// Check if pred is now last
if (pred.next == null)
last = pred;
  
return true;
}

LinkedList1Demo:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;


/**
This class is used to demonstrate
the operations in the LinkedList1 class.
*/


public class LinkedList1Demo extends JFrame
{   
private LinkedList1 ll;
private JTextArea listView;
private JTextField cmdTextField;
private JTextField resultTextField;
  
public LinkedList1Demo()
{
ll = new LinkedList1();
listView = new JTextArea();
cmdTextField = new JTextField();
resultTextField = new JTextField();
  
// Create a panel and label for result field
JPanel resultPanel = new JPanel(new GridLayout(1,2));
resultPanel.add(new JLabel("Command Result"));
resultPanel.add(resultTextField);
resultTextField.setEditable(false);
add(resultPanel, BorderLayout.NORTH);
  
// Put the textArea in the center of the frame
add(listView);
listView.setEditable(false);
listView.setBackground(Color.WHITE);
  
// Create a panel and label for the command text field
JPanel cmdPanel = new JPanel(new GridLayout(1,2));
cmdPanel.add(new JLabel("Command:"));
cmdPanel.add(cmdTextField);
add(cmdPanel, BorderLayout.SOUTH);  
cmdTextField.addActionListener(new CmdTextListener());
  
// Set up the frame
setTitle("Linked List Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
  
/**
Private class that responds to the command that
the user types into the command entry text field.
*/
  
private class CmdTextListener
implements ActionListener
{   
public void actionPerformed(ActionEvent evt)
{
String cmdText = cmdTextField.getText();
Scanner sc = new Scanner(cmdText);
String cmd = sc.next();
if (cmd.equals("add"))
{
if (sc.hasNextInt())
{
// add index element
int index = sc.nextInt();
String element = sc.next();
ll.add(index, element);   
}
else
{  
// add element
String element = sc.next();
ll.add(element);   
}
listView.setText(ll.toString());
pack();
return;
}
if (cmd.equals("remove"))
{
if (sc.hasNextInt())
{
// remove index
int index = sc.nextInt();
String res = ll.remove(index);
resultTextField.setText(res);   
}
else
{
// remove element
String element = sc.next();
boolean res = ll.remove(element);
String resText = String.valueOf(res);
resultTextField.setText(resText);
}
listView.setText(ll.toString());
pack();
return;
}
if (cmd.equals("isempty"))
{
String resText = String.valueOf(ll.isEmpty());
resultTextField.setText(resText);
return;
}
if (cmd.equals("size"))
{
String resText = String.valueOf(ll.size());
resultTextField.setText(resText);
return;
}
}
}
  
/**
The main method creates an instance of the
LinkedList1Demo class which causes it to
display its window.
*/
  
public static void main(String [ ] args)
{
new LinkedList1Demo();
}   
}

Solutions

Expert Solution

Code is as follows:

LinkedList1:

class LinkedList1 {

   private class Node {
       String value;
       Node next;

       Node(String val, Node n) {
           value = val;
           next = n;
       }

       Node(String val) {
           // Call the other (sister) constructor.
           this(val, null);
       }
   }

   private Node first; // list head
   private Node last; // last element in list

   public LinkedList1() {
       first = null;
       last = null;
   }

   public boolean isEmpty() {
       return first == null;
   }

   private Node reverseRecursively(Node node) {
       Node newHead;

       // base case - tail of original linked list
       if ((node.next == null)) {
           return node;
       }
       newHead = reverseRecursively(node.next);

       // reverse the link e.g. C->D->null will be null
       node.next.next = node;
       node.next = null;
       return newHead;
   }

   public void reverse() {
       last = first;
       first = reverseRecursively(first);
   }

   // function to swap nodes 'currX' and 'currY' in a
   // linked list without swapping data
   public Node swapNodes( Node head_ref, Node currX,
   Node currY, Node prevY)
   {
   // make 'currY' as new head
   head_ref = currY;
  
   // adjust links
   prevY.next = currX;
  
   // Swap next pointers
   Node temp = currY.next;
   currY.next = currX.next;
   currX.next = temp;
   return head_ref;
   }
  
   // function to sort the linked list using
   // recursive selection sort technique
   public Node sort( Node head)
   {
   // if there is only a single node
   if (head.next == null)
   return head;
  
   // 'min' - pointer to store the node having
   // minimum data value
   Node min = head;
  
   // 'beforeMin' - pointer to store node previous
   // to 'min' node
   Node beforeMin = null;
   Node ptr;
  
   // traverse the list till the last node
   for (ptr = head; ptr.next != null; ptr = ptr.next)
   {
  
   // if true, then update 'min' and 'beforeMin'
   if (ptr.next.value.compareTo(min.value)<0)
   {
   min = ptr.next;
   beforeMin = ptr;
   }
   }
  
   // if 'min' and 'head' are not same,
   // swap the head node with the 'min' node
   if (min != head)
   head = swapNodes(head, head, min, beforeMin);
  
   // recursively sort the remaining list
   head.next = sort(head.next);
  
   return head;
   }
  
   // function to sort the given linked list
   public void sort()
   {
   // if list is empty
   if (first == null)
   return;
  
   // sort the list using recursive selection
   // sort technique
   first = sort(first);
  
   //after getting first we have to change the last
   Node temp = first;
   while(temp.next!=null) {
       temp = temp.next; //go upto last
   }
   last = temp;   //change the last
   }
   public int size() {
       int count = 0;
       Node p = first;
       while (p != null) {
           // There is an element at p
           count++;
           p = p.next;
       }
       return count;
   }

   public void add(String e) {
       if (isEmpty()) {
           first = new Node(e);
           last = first;
       } else {
           // Add to end of existing list
           last.next = new Node(e);
           last = last.next;
       }
   }

   public void add(int index, String e) {
       if (index < 0 || index > size()) {
           String message = String.valueOf(index);
           throw new IndexOutOfBoundsException(message);
       }

       // Index is at least 0
       if (index == 0) {
           // New element goes at beginning
           first = new Node(e, first);
           if (last == null)
               last = first;
           return;
       }

       Node pred = first;
       for (int k = 1; k <= index - 1; k++) {
           pred = pred.next;
       }

       pred.next = new Node(e, pred.next);

       if (pred.next.next == null)
           last = pred.next;
   }

   public String toString() {
       StringBuilder strBuilder = new StringBuilder();

       Node p = first;
       while (p != null) {
           strBuilder.append(p.value + "\n");
           p = p.next;
       }
       return strBuilder.toString();
   }

   public String remove(int index) {
       if (index < 0 || index >= size()) {
           String message = String.valueOf(index);
           throw new IndexOutOfBoundsException(message);
       }

       String element; // The element to return
       if (index == 0) {
           // Removal of first item in the list
           element = first.value;
           first = first.next;
           if (first == null)
               last = null;
       } else {

           Node pred = first;

           for (int k = 1; k <= index - 1; k++)
               pred = pred.next;

           element = pred.next.value;

           pred.next = pred.next.next;

           if (pred.next == null)
               last = pred;
       }
       return element;
   }

   public boolean remove(String element) {
       if (isEmpty())
           return false;

       if (element.equals(first.value)) {

           first = first.next;
           if (first == null)
               last = null;
           return true;
       }

       Node pred = first;
       while (pred.next != null && !pred.next.value.equals(element)) {
           pred = pred.next;
       }

       if (pred.next == null)
           return false;

       pred.next = pred.next.next;

       // Check if pred is now last
       if (pred.next == null)
           last = pred;

       return true;
   }
}

***********************************************************************************************************************************

LinkedList1Demo:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/**
* This class is used to demonstrate the operations in the LinkedList1 class.
*/

public class LinkedList1Demo extends JFrame {
   private LinkedList1 ll;
   private JTextArea listView;
   private JTextField cmdTextField;
   private JTextField resultTextField;

   public LinkedList1Demo() {
       ll = new LinkedList1();
       listView = new JTextArea();
       cmdTextField = new JTextField();
       resultTextField = new JTextField();

       // Create a panel and label for result field
       JPanel resultPanel = new JPanel(new GridLayout(1, 2));
       resultPanel.add(new JLabel("Command Result"));
       resultPanel.add(resultTextField);
       resultTextField.setEditable(false);
       add(resultPanel, BorderLayout.NORTH);

       // Put the textArea in the center of the frame
       add(listView);
       listView.setEditable(false);
       listView.setBackground(Color.WHITE);

       // Create a panel and label for the command text field
       JPanel cmdPanel = new JPanel(new GridLayout(1, 2));
       cmdPanel.add(new JLabel("Command:"));
       cmdPanel.add(cmdTextField);
       add(cmdPanel, BorderLayout.SOUTH);
       cmdTextField.addActionListener(new CmdTextListener());

       // Set up the frame
       setTitle("Linked List Demo");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       pack();
       setVisible(true);
   }

   /**
   * Private class that responds to the command that the user types into the
   * command entry text field.
   */

   private class CmdTextListener implements ActionListener {
       public void actionPerformed(ActionEvent evt) {
           String cmdText = cmdTextField.getText();
           Scanner sc = new Scanner(cmdText);
           String cmd = sc.next();
           if (cmd.equals("add")) {
               if (sc.hasNextInt()) {
                   // add index element
                   int index = sc.nextInt();
                   String element = sc.next();
                   ll.add(index, element);
               } else {
                   // add element
                   String element = sc.next();
                   ll.add(element);
               }
               listView.setText(ll.toString());
               pack();
               return;
           }
           if (cmd.equals("remove")) {
               if (sc.hasNextInt()) {
                   // remove index
                   int index = sc.nextInt();
                   String res = ll.remove(index);
                   resultTextField.setText(res);
               } else {
                   // remove element
                   String element = sc.next();
                   boolean res = ll.remove(element);
                   String resText = String.valueOf(res);
                   resultTextField.setText(resText);
               }
               listView.setText(ll.toString());
               pack();
               return;
           }
           if (cmd.equals("isempty")) {
               String resText = String.valueOf(ll.isEmpty());
               resultTextField.setText(resText);
               return;
           }
           if (cmd.equals("size")) {
               String resText = String.valueOf(ll.size());
               resultTextField.setText(resText);
               return;
           }
           if(cmd.equals("reverse")) {
               ll.reverse();
               listView.setText(ll.toString());
               pack();
               return;
           }
           if(cmd.equals("sort")) {
               ll.sort();
               listView.setText(ll.toString());
               pack();
               return;
           }
       }
   }

   /**
   * The main method creates an instance of the LinkedList1Demo class which causes
   * it to display its window.
   */

   public static void main(String[] args) {
       new LinkedList1Demo();
   }
}

*******************************************************************************************************************************

Output:

before sort command

after sort command

before reverse command

after reverse command


Related Solutions

Using Java create a program that does the following: Modify the LinkedList1 class by adding sort()...
Using Java create a program that does the following: Modify the LinkedList1 class by adding sort() and reverse() methods. The reverse method reverses the order of the elements in the list, and the sort method rearranges the elements in the list so they are sorted in alphabetical order. Do not use recursion to implement either of these operations. Extend the graphical interface in the LinkedList1Demo class to support sort and reverse commands, and use it to test the new methods....
Write in Java Modify the parent class (Plant) by adding the following abstract methods:(The class give...
Write in Java Modify the parent class (Plant) by adding the following abstract methods:(The class give in the end of question) a method to return the botanical (Latin) name of the plant a method that describes how the plant is used by humans (as food, to build houses, etc) Add a Vegetable class with a flavor variable (sweet, salty, tart, etc) and 2 methods that return the following information: list 2 dishes (meals) that the vegetable can be used in...
Modify StudentLinkedList class by adding the following methods: printStudentList: print by calling and printing “toString” of...
Modify StudentLinkedList class by adding the following methods: printStudentList: print by calling and printing “toString” of every object in the linkedList. Every student object to be printed in a separate line.  deleteStudentByID(long id): delete student object from the list whose ID is matching with the passed parameter.  sortListByID(): sort the linkedlist according to students IDs.  findMarksAverage(): find the average of all marks for all students in the list.  findMinMark(int markIndex): find the student with the minimum...
Problem 3: Modify StudentLinkedList class by adding the following methods:  printStudentList: print by calling and...
Problem 3: Modify StudentLinkedList class by adding the following methods:  printStudentList: print by calling and printing “toString” of every object in the linkedList. Every student object to be printed in a separate line.  deleteStudentByID(long id): delete student object from the list whose ID is matching with the passed parameter.  sortListByID(): sort the linkedlist according to students IDs.  findMarksAverage(): find the average of all marks for all students in the list.  findMinMark(int markIndex): find the student...
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
C++ Modify the class unorderedList to include a recursive forward print and a recursive reverse print...
C++ Modify the class unorderedList to include a recursive forward print and a recursive reverse print Make your unorderedList a list of characters instead of integers Insert ten characters into the list and print it out both ways #include <iostream> #include <string> #include <cstdlib> using namespace std; struct node { int info; node* next; }; class unorderedList { private: int length; node* listPtr; public: unorderedList() {length = 0; listPtr = NULL;} void makeEmpty(); void insertItem(int item); void printList(); bool isFull()...
In Java: Write two advanced sorting methods of your choice: (Shell Sort OR Radix Sort) AND...
In Java: Write two advanced sorting methods of your choice: (Shell Sort OR Radix Sort) AND (Merge Sort OR Quick Sort). If you choose Shell Sort, experiment with different incremental sequences to see how they affect the algorithm's run time efficiency (count the number of comparisons and exchanges). If you choose to implement Radix Sort, answer the following question as well: Can you write a version of Radix Sort for String objects? If yes, explain how. If not, explain why....
Complete the coding/testing of the heap sort method we began in class. Then modify your program...
Complete the coding/testing of the heap sort method we began in class. Then modify your program so that it outputs a comparison of the actual number of swaps it performs to the predicted number of swaps, and a comparison of the actual sort effort to the predicted and minimum sort effort. The output should be formatted exactly as shown below. Actual swaps = xxxx; Predicted swaps = xxxx Actual sort effort = xxxx; Predicted sort effort = xxxx; Min sort...
Instructions Modify the Product class from the Practice Exercise 7 by adding a quantity member. Include...
Instructions Modify the Product class from the Practice Exercise 7 by adding a quantity member. Include a getter and setter, using decorators, and modify the appropriate constructor to also accept a quantity parameter. Then modify the inventory.py file from the practice exercise to include quantity values in the constructor calls with a quantity of 100 for product1 (hammers) and 3000 for product2 (nails). Add print statements to display the quantity values as shown in the Expected Output included below. Submission...
C++ Tony Gaddis 8.11: Using Files-- String Selection Sort Modification Modify the selectionSort function presented in...
C++ Tony Gaddis 8.11: Using Files-- String Selection Sort Modification Modify the selectionSort function presented in this chapter so it sorts an array of strings instead of an array of ints. Test the function with a driver program that reads an integer, N, from standard input and then reads the first N strings from a file called href="asfunction:_root.doTutor,7,CPP">names. (Assume that N is less than or equal to 20.) Input Validation. If N read in from standard input is greater than...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT