Question

In: Computer Science

In Java: In the SingleLinkedList defined in the textbook Section 2.5 (named KWSingleLinkedList there), add the...

In Java:

In the SingleLinkedList defined in the textbook Section 2.5 (named KWSingleLinkedList there), add the following methods:

KWSingleLinkedList<String> Names = new KWSingleLinkedList,.();

names.addFirst("Sam");

names.addFirst("Harry");

names.addFirst("Dick");

names.addFirst("Tom");

  • Write method indexOf.
  • Write the remove method whose method heading follows
/** Remove the first occurrence of element item.
    @param item The item to be removed
    @return true if item is found and removed; otherwise, return false.
*/
public boolean remove(E item)
  • Write the following method add
/** Insert a new item before the one at position index, starting at 0
     for the list head. The new item is inserted between the one at
     position index‐1 and the one formerly at position index.
    @param index The index where the new item is to be inserted
    @param item The item to be inserted
    @throws IndexOutOfBoundsException if the index is out of range
*/
public void add(int index, E item)
  • Write a main program to test and demonstrate the functions of the class.

Solutions

Expert Solution

public class LinkedListDemo {
    public static void main(String[] args) {
        KWSingleLinkedList<String> names = new KWSingleLinkedList();
        names.addFirst("Sam");
        names.addFirst("Harry");
        names.addFirst("Dick");
        names.addFirst("Tom");

        names.printList();

        System.out.println("Removing Harry: " + names.remove("Harry"));
        names.printList();


        System.out.println("Adding Srinu at index 2: ");
        names.add(2, "Srinu");
        names.printList();
    }
}

//Linked list class
class KWSingleLinkedList<E> {
    private Node<E> head = null;

    //adding a value
    public void addFirst(E value) {
        //first node
        if (head == null) {
            head = new Node(value);
            return;
        }
        //insert at first
        Node temp = new Node(value);
        temp.setNext(head);
        head = temp;
    }

    /**
     * Print the entire list
     */
    //print the list
    public void printList() {
        System.out.println();
        System.out.printf("List::: ");
        Node temp = head;
        //traverse up to end
        while (temp != null) {
            System.out.print(temp.getValue() + " "); //print value
            temp = temp.getNext();
        }
        System.out.println();
        System.out.println();
    }

    /**
     * Remove the first occurrence of element item.
     *
     * @param item The item to be removed
     * @return true if item is found and removed; otherwise, return false.
     */
    public boolean remove(E item) {
        //empty list
        if (head == null) {
            return false;
        }
        //remove at first
        if (head.getValue().equals(item)) {
            head = head.getNext();
            return true;
        }
        Node<E> temp = head;
        Node<E> prev = null;
        Node<E> prevToPrev = null;
        boolean found = false;
        //traverse to end
        while (temp != null) {
            //found value
            if (temp.getValue().equals(item)) {
                prevToPrev = prev; //hold pointer to prev of item
                found = true;
            }
            prev = temp;
            temp = temp.getNext();
            if (found) {
                break;
            }
        }
        //remove item
        if (prevToPrev != null) {
            prev.setNext(null);
            prevToPrev.setNext(temp);
            return true;
        }
        return false;
    }


    /**
     * Insert a new item before the one at position index, starting at 0
     * for the list head. The new item is inserted between the one at
     * position index‐1 and the one formerly at position index.
     *
     * @param index The index where the new item is to be inserted
     * @param item  The item to be inserted
     * @throws IndexOutOfBoundsException if the index is out of range
     */
    public void add(int index, E item) {
        //throw index bounds exception if invalid index
        if (index < 0 || index > getSize()) {
            throw new IndexOutOfBoundsException();
        }
        //add first if index is 0
        if (index == 0) {
            addFirst(item);
            return;
        }
        int count = 0;

        Node<E> temp = head;
        Node<E> prev = null;
        //traverse until count is less than index
        while (temp != null && count < index) {
            prev = temp; //hold prev pointer of temp
            count++;
            temp = temp.getNext();
        }
        Node<E> newNode = new Node<>(item); //creating new node
        //inserting at given index
        prev.setNext(newNode);
        newNode.setNext(temp);
    }

    public int getSize() {
        Node<E> temp = head;
        int size = 0;
        while (temp != null) {
            size++;
            temp = temp.getNext();
        }
        return size;
    }
}

class Node<T> {
    private T value;
    private Node next;

    public Node(T value) {
        this.value = value;
        this.next = null;
    }

    public T getValue() {
        return value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

Related Solutions

Java Language Add a recursive method to the program shown in the previous section that states...
Java Language Add a recursive method to the program shown in the previous section that states how many nodes does the stack have. Code: class Stack { protected Node top; Stack() { top = null; } boolean isEmpty() { return( top == null); } void push(int v) { Node tempPointer; tempPointer = new Node(v); tempPointer.nextNode = top; top = tempPointer; } int pop() { int tempValue; tempValue = top.value; top = top.nextNode; return tempValue; } void printStack() { Node aPointer...
Java Language Add a recursive method to the program shown in the previous section that allows...
Java Language Add a recursive method to the program shown in the previous section that allows remove the last node from the stack. Code: class Stack { protected Node top; Stack() { top = null; } boolean isEmpty() { return( top == null); } void push(int v) { Node tempPointer; tempPointer = new Node(v); tempPointer.nextNode = top; top = tempPointer; } int pop() { int tempValue; tempValue = top.value; top = top.nextNode; return tempValue; } void printStack() { Node aPointer...
Java Language Add a recursive method to the program shown in the previous section that allows...
Java Language Add a recursive method to the program shown in the previous section that allows insert a value at the end of the stack. Code: class Stack { protected Node top; Stack() { top = null; } boolean isEmpty() { return( top == null); } void push(int v) { Node tempPointer; tempPointer = new Node(v); tempPointer.nextNode = top; top = tempPointer; } int pop() { int tempValue; tempValue = top.value; top = top.nextNode; return tempValue; } void printStack() {...
According to the textbook, the defined contribution plan and defined benefit plan are the most popular...
According to the textbook, the defined contribution plan and defined benefit plan are the most popular pension plans used by employers. Employers have changed from traditionally defined benefit plans to defined contribution plans with no major company establishing a traditional pension plan in the past decade. Differentiate between the defined contribution pension plan and the defined benefit plan. What are the major differences in accounting for defined contribution plans and defined benefit plans? Assess the most likely reasons this trend...
In java: -Create a class named Animal
In java: -Create a class named Animal
Add      0.5       kg,        50mg   and       2.5        dg. Reduce the results to grams.
Add      0.5       kg,        50mg   and       2.5        dg. Reduce the results to grams.
IN JAVA: Repeat Exercise 28, but add the methods to the LinkedStack class. Add the following...
IN JAVA: Repeat Exercise 28, but add the methods to the LinkedStack class. Add the following methods to the LinkedStacked class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of these methods by accessing the internal variables of the LinkedStacked, not by calling the previously defined public methods of the class. - String toString()—creates and returns a string that correctly represents the current stack....
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
During the reading of the textbook there is a section about call provision. This is when...
During the reading of the textbook there is a section about call provision. This is when a corporation has the right to call the bonds for redemption. The book says that that the company must pay the bondholders an amount great than the par value if they are called. They usually do this if interest rates drop. The reason being is that bonds and interest rates have an inverse relationship. After the company calls the bonds they will issue out...
Java - Design a class named Account that contains: A private String data field named accountNumber...
Java - Design a class named Account that contains: A private String data field named accountNumber for the account (default AC000). A private double data field named balance for the account (default 0). A private double data field named annualIntRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate. A private Date data field named dateCreated that stores the date when the account was created. A no-arg constructor that creates a default account....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT