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

For a LinkedList in Java how do I - Add a method named replace() that takes...
For a LinkedList in Java how do I - Add a method named replace() that takes in two parameters (the data object to replaced, followed by the one to be inserted) that will remove the first occurrence of the item to be replaced and add the second parameter to the list. The method returns a boolean - true if the item to be replaced was found, false if not - Add an instance method named showList() (no parameters or return...
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() {...
Step 1: Create a new Java project named ContainerPartyProject --------- Step 2: Add a ContainerParty class...
Step 1: Create a new Java project named ContainerPartyProject --------- Step 2: Add a ContainerParty class to your project. It should contain:             - The date of the party             - A list of people attending             - A list of containers at the party             - The address of the party (this can be either a String or a Class) --------- Step 3: Add a Container class in your project. It should be an abstract class. Your Container class...
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...
My add method is not working to add elements into an arrayList in java. This is...
My add method is not working to add elements into an arrayList in java. This is the error message I keep getting: Exception in thread "main" java.lang.NullPointerException    at assignment1.ArrayBag.add(ArrayBag.java:50)    at assignment1.Main.main(Main.java:21) BUILD FAILED (total time: 0 seconds) The following are all the methods I've created. /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package...
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.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT