Question

In: Computer Science

Based on a Node class; Use Java to implement the OrderedList class which represents an ordered...

Based on a Node class;

Use Java to implement the OrderedList class which represents an ordered singly linked list that cannot contain any duplicates. Note that items in the OrderedList are always kept in descending order. Complete the class with the following methods.

  • Default constructor
    Create an empty list i.e., head is null.
  • boolean insert(int data)
    Insert the given data into the list at the proper location in the list. If the insertion is successful, the function returns true; otherwise, returns false.
  • boolean delete(int data)
    Delete the node that contains the given data from the list. If the deletion is successful, the function returns true; otherwise, returns false.
  • int find(int data)
    Search and return the index to the node that contains the data. Note that the index starts from 0. If it is not found, return -1.
  • int count()
    Count and return the number of nodes in the list
  • String toString()
    Return the string representation of this List where all data in the list are enclosed in square brackets [ ].

Then write the program that accepts a sequence of commands and print out the number of successful insertions, the number of successful deletions, the number of successful searches (through the “find” command), the number of items remaining in the list after executing all commands and the final contents of the list.

There are 3 commands which are “insert”, “delete” and “find”.

Input

Line 1: The number of transactions m on the list, where 1  m 200.

Line 2 to m+1: A string command (“insert”, “delete”, “find”) followed by an integer n (separated by a space).

  • • “insert” means insert n into the list
  • • “delete” means delete n from the list
  • • “find” means find n in the list

Output

Line 1: Display 4 integers (each number is separated by a space) which are:

  • • the number of successful insertions,
  • • the number of successful deletions,
  • • the number of items found (from the command “find”), and
  • • the number of items remaining in the list

Line 2: The final contents of the list

Sample Input

Sample Output

3

insert 1

delete 5

find 2

1 0 0 1

[ 1 ]

8

find 10

insert 3

insert 2

insert 1

delete 4

delete 3

insert 1

find 2

3 1 1 2

[ 2 1 ]

Solutions

Expert Solution

Here I have provided the solution. Ihave taken the attributes of the Node class randomly as val and next. You can configure it as required. The rest of it is the same. Also I have used the Scanner class for input.

import java.util.Scanner;

class Node
{
    public int val;
    public Node next;

    Node(int i)
    {
        this.val = i;
        this.next = null;
    }
}


public class OrderedList
{
    public Node head;
    OrderedList(){
        this.head = null;
    }

    public boolean insert(int data)
    {
        Node newNode = new Node(data);
        if(head == null)    head = newNode;
        else{
            Node trav = head;
            while(trav.next!=null){
                if(trav.val == data)    return false;
                trav = trav.next;
            }
            if(trav.val == data)    return false;
            trav.next = newNode;
        }
        return true;
    }

    public boolean delete(int data)
    {
        if(head.val == data)    head = head.next;
        else{
            Node trav = head, prev = null;
            while(trav != null && trav.val != data){
                prev = trav;
                trav = trav.next;
            }
            if(trav == null)    return false;
            prev.next = trav.next;
        }
        return true;
    }

    public int find(int data)
    {
        Node trav = head;
        int i = 0;
        while(trav!=null){
            if(trav.val == data)    return i;
            trav = trav.next;
            i++;
        }
        return -1;
    }

    public int count()
    {
        Node trav = head;
        int i = 0;
        while(trav !=null){
            trav = trav.next;
            i++;
        }
        return i;
    }

    public String toString()
    {
        String output = "[";
        Node trav = head;
        while(trav!=null){
            output += " "+trav.val;
            trav = trav.next;
        }
        output += " ]";
        return output;
    }

    public static void main(String [] args)
    {
        Scanner sc = new Scanner(System.in);
        OrderedList ol = new OrderedList();
        String command[];
        int n = sc.nextInt();
        int succ_insert = 0, succ_delete = 0, succ_find = 0, num_items = 0;
        while(n >= 0)
        {
            command = sc.nextLine().split(" ");
            if(command[0].equals("insert")){
                if(ol.insert(Integer.parseInt(command[1]))) {succ_insert++; num_items++;}
            }
            else if (command[0].equals("delete")){
                if(ol.delete(Integer.parseInt(command[1]))) {succ_delete++; num_items--;}
            }
            else if(command[0].equals("find"))
            {
                if(ol.find(Integer.parseInt(command[1])) > -1)  succ_find++;
            }
            n--;
        }
        System.out.println(succ_insert+" "+succ_delete+" "+succ_find+" "+num_items);
        System.out.println(ol.toString());
    }
}

Related Solutions

JAVA - Design and implement a class called Flight that represents an airline flight. It should...
JAVA - Design and implement a class called Flight that represents an airline flight. It should contain instance data that represent the airline name, the flight number, and the flight’s origin and destination cities. Define the Flight constructor to accept and initialize all instance data. Include getter and setter methods for all instance data. Include a toString method that returns a one-line description of the flight. Create a driver class called FlightTest, whose main method instantiates and updates several Flight...
in java Design and implement a class called Dog that contains instance data that represents the...
in java Design and implement a class called Dog that contains instance data that represents the dog’s name and age. Define the Dog constructor to accept and initialize instance data. Include getter and setter methods for the name and age. Include a method to compute and return the age of the dog in “person years” (seven times the dog’s age). Include a toString method that returns a one-line description of the dog. Create a Tester class called Kennel, whose main...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
Overview For this assignment, implement and use the methods for a class called Seller that represents...
Overview For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson. The Seller class Use the following class definition: class Seller { public: Seller(); Seller( const char [], const char[], const char [], double ); void print(); void setFirstName( const char [] ); void setLastName( const char [] ); void setID( const char [] ); void setSalesTotal( double ); double getSalesTotal(); private: char firstName[20]; char lastName[30]; char ID[7]; double salesTotal; };...
Overview For this assignment, implement and use the methods for a class called Seller that represents...
Overview For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson. The Seller class Use the following class definition: class Seller { public: Seller(); Seller( const char [], const char[], const char [], double ); void print(); void setFirstName( const char [] ); void setLastName( const char [] ); void setID( const char [] ); void setSalesTotal( double ); double getSalesTotal(); private: char firstName[20]; char lastName[30]; char ID[7]; double salesTotal; };...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int size; public CircularLinkedList() { tail= null; size = 0; } public int size(){ return size; } public boolean isEmpty() { return size==0; } //if list is not empty return the first element public E first() { if (isEmpty()) return null; //code here return 0; } //if list not empty return last element public E last() { if (isEmpty()) return null; return tail.getElement(); } /*...
in java This class will require the following fields: Node<T> head: the first Node in the...
in java This class will require the following fields: Node<T> head: the first Node in the chain Node<T> tail: the last Node in the chain int size: Keeps a count of the number of Nodes in the chain Your LinkedList class must also support the following public methods. LinkedList(): A default constructor sets both pointers to null and sets the size to 0. int size(): Returns the size of the LinkedList. void push_back(T): Creates a new Node and assigns it...
class nodeType                    // class used to implement a node { public:         int data;   &n
class nodeType                    // class used to implement a node { public:         int data;                        // data member of node         nodeType * next;        // pointer member of node }; int main() {         int x;         nodeType * head =________ ;                     // initialize head pointer         nodeType * tail = _______ ;                        // initialize tail pointer _______ * p;                                                 // create an auxiliary pointer to a node         for (x = 0; x < 10; ++x)         {                 p =   _________ nodeType; // create a node ___________ = x + 10;                                // store...
Define and implement a class named Coach, which represents a special kind of person. It is...
Define and implement a class named Coach, which represents a special kind of person. It is to be defined by inheriting from the Person class. The Coach class has the following constructor: Coach(string n, int sl) // creates a person with name n, whose occupation // is “coach” and service length is sl The class must have a private static attribute static int nextID ; which is the unique personID of the next Coach object to be created. This is...
For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson.
For this assignment, implement and use the methods for a class called Seller that represents information about a salesperson.The Seller classUse the following class definition:class Seller { public:   Seller();   Seller( const char [], const char[], const char [], double );        void print();   void setFirstName( const char [] );   void setLastName( const char [] );   void setID( const char [] );   void setSalesTotal( double );   double getSalesTotal(); private:   char firstName[20];   char lastName[30];   char ID[7];   double salesTotal; };Data MembersThe data members for the class are:firstName holds the Seller's first namelastName holds the Seller's last nameID holds the Seller's id numbersalesTotal holds the Seller's sales totalConstructorsThis class has two constructors. The default constructor (the one that takes...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT