Question

In Java The following Java implementation of a class Node is given: private class Node<Object> {...

In Java

The following Java implementation of a class Node is given:

private class Node<Object>

{

Node()

{

this(null, null);

}

Node(Object d)

{

this(d, null);

}

Node(Object d, Node n)

{

data = d; next = n;

}

Object data; Node next;

}

Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a reference to the header node.

Using the class Node described above, write a MySingleLinkedList class in Java includes methods to:

int size() - return the size of the linked list.

void print() - print the linked list.

boolean contains(Object x) - test if a value x is contained in the linked list.

boolean add(Object x) - add a value x if it is not already contained in the linked list.

boolean remove(Object x) - remove a value x if it is contained in the linked list.

Very important!

In the implementation of the MySingleLinkedList class resolution it is not allowed to use the interface Iterator.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
public class MySingleLinkedList<Object> {

    /* below definition of Node was given in question */
    private class Node<Object>
    {
        Node()
        {
            this(null, null);
        }
        Node(Object d)
        {
            this(d, null);
        }
        Node(Object d, Node n)
        {
            data = d; next = n;
        }

        Object data;
        Node next;
    }

    //declaration of only data member head
    Node<Object> head;

    /* Below is size function which will run till the end of list
    * How it will find end ?
    * end node next will be null
    *
    * So for each non null node encounter it will increment it's count value
    * and finally return it's node count value*/
    int size(){
        int count = 0;
        Node<Object> temp = head;
        while(temp != null){
            ++count;
            temp = temp.next;
        }
        return  count;
    }

    /*Below function will iterate through list
    * and print it's content untill end*/
    void print(){
        Node<Object> temp = head;
        while(temp != null){
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    /* iterate untill end
    * and check whether data x is present or not
    * if present then set the flag (which represent found) to true
    *
    * finally return flag
    * Note if data x is not present then flag value remain false
    * and as a result false value will returned which represent data is not in list*/
    boolean contains(Object x){
        boolean flag = false;
        Node<Object> temp = head;
        while(temp != null){
            if(temp.data == x){
                flag = true;
            }
            temp = temp.next;
        }
        return  flag;
    }

    /*IMPORTANT NOTE
    * i am adding node to begining of list
    * as it was not mentioned where to add
    * why i adding to begining
    * bcoz it will reduce running time of code
    *
    * if x is already present then don't add it and return false
    * else
    * add it to begining and return true*/
    boolean add(Object x){
        if(this.contains(x)){
            return false;
        }
        else{
            Node<Object> temp = new Node<>(x,head);
            this.head = temp;
            return true;
        }
    }

    /*first we have to check whether data is present or not
    * bcoz if x is not present then there is no meaning of removing x
    *
    * so
    *
    * if present then remove it*/

    boolean remove(Object x){
        if(this.contains(x)){
            Node<Object> temp = head;
            Node<Object> temp2 = temp;
            while(temp.data != x){
                temp2 = temp;
                temp = temp.next;
            }
            if(temp.next == null){
                temp2.next = null;
            }
            else {
                temp2.next = temp.next;
            }
            return true;
        }
        return  false;
    }

    /* Main to test functionality
    * Please add or test code according to your need*/
    
    public static void main(String[] args) {
        MySingleLinkedList<Integer> list = new MySingleLinkedList<>();
        /*adding data by running a loop */
        for(int i=0;i<10;++i){
            list.add(i);
        }
        System.out.println("Initially linked list contain : ");
        list.print();

        System.out.println("Size of linked list : " + list.size());

        if(list.contains(5)){
            System.out.println("our list contain 5");
        }
        else {
            System.out.println("our list does not contain 5");
        }

        if(list.remove(6)){
            System.out.println("6 was removed and updated list is :");
            list.print();
        }
        else {
            System.out.println("6 was not present in list");
        }
    }
}

//sample output

Run MySingleLinkedList C:|Program Files\Java\jdkl.8.0 131\binljava Initially linked list contain: 9 8 7 6 5 4 3 2 1 0 Size

Add a comment
Know the answer?
Add Answer to:
In Java The following Java implementation of a class Node is given: private class Node<Object> {...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

    Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...

  • 1. Create a class MLL, a singly linked, non-circular list where each node only has one...

    1. Create a class MLL, a singly linked, non-circular list where each node only has one link next and the list has a head and a tail link (think about implementation of node). The MLL class also implements the Iterable interface. The following should be implemented as well: 2. Add the methods to the MLL class: a. iterator() to implement the Iterable interface. This method returns an instance of MLLI initialized appropriately. b. addFirst( value) that adds a value to...

  • Write a complete bag class implementation using linked implementation. The linked bag class name must be...

    Write a complete bag class implementation using linked implementation. The linked bag class name must be LinkedBag and name your test program as LinkedBagDemo. Your test program should include following test conditions: 1. Get the number of items currently in the bag 2. See whether the bag is full 3. See whether the bag is empty 4. Add a given object to the bag 5. Remove an unspecified (not random) object from the bag 6. Remove an occurrence of a...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • On Java: Problems Problem 1. (Deque) Hints: my Use a doubly-linked list Node to implement the...

    On Java: Problems Problem 1. (Deque) Hints: my Use a doubly-linked list Node to implement the API — each node in the list stores a generic item, and references next and prev to the next and previous nodes in the list null itemi → item2 item3 ... itemn null Instance variables wy Reference to the front of the deque, Node first my Reference to the back of the deque, Node last my Size of the deque, int n + LinkedDeque...

  • can you solve it in java please Create the following: 1. Class Invoice ( the node...

    can you solve it in java please Create the following: 1. Class Invoice ( the node ) that includes three instance variables:     int No; // the Invoice No             String CustName; // the Customer name             int Amount; // the Invoice Amount Invoice next; // points to the next Invoice Default and overloaded constructors 2. Class Shop that includes three instance variables: Invoice head; Invoice Tail; Your class should have the following: • A method that initializes the instance variables....

  • Question B1 You are given the following Java classes: public class Queue { private static class...

    Question B1 You are given the following Java classes: public class Queue { private static class Node { Object object; Node next; Node () { object = null; next = null; } Node (Object object, Node next) { this.object = object; this.next = next; private Node header; private int size = 0; // size shows the no of elements in queue public Object dequeue () { if (size == 0 ) { return null; else { Object remove_object = header.object;...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT