Question

In: Computer Science

The aim of this lab session is to make you familiar with implementing a linked list....

The aim of this lab session is to make you familiar with implementing a linked list. In this lab you will complete the partially implemented LinkedIntegerList.

Specifically, you will implement the following methods.

• public boolean remove(int value)

• public int removeAt(int index)

• public boolean set(int index, int value)

• public int indexOf(int value)

Task-1

Add a new class named Lab3Tester class to test the current implementation of the linked list. (Note: you may reuse the code from SimpleIntegerListTester class.)

Make sure your code compiles and executes without any errors.

Task 2: Implement the remove Method

1. Implement the remove method in the LinkedIntegerList class. Make sure your code is commented and properly indented.

2. Test the new implementation using Lab3Tester class.

3. Commit code changes.

Task 3: Implement the removeAt Method

1. Implement the removeAt method in the LinkedIntegerList class. Make sure your code is commented and properly indented.

2. Test the new implementation using Lab3Tester class.

3. Commit code changes.


LInkedintegrelist :

public class LinkedIntegerList implements SimpleIntegerListADT {

   //Instance variables
   private IntegerNode head;
   private int itemCount;

   /**
   * Default constructor.
   */
   public LinkedIntegerList() {
       super();
       this.head = null;
       this.itemCount = 0;
   }

   @Override
   public boolean add(int value) {
       IntegerNode newNode = new IntegerNode(value);
       if(null == this.head) { //Adding to empty list
           this.head = newNode; //Set new node as head
           this.itemCount = 1; //Set item count to 1
           return true;
       }
       else {
           //Find the last node.
           IntegerNode currNode = this.head;
           //Last node does not have a next node (null). Therefore, update the currNode to current nodes' next while it is not null.
           while(null != currNode.getNext())
               currNode = currNode.getNext();
           //Set next of last node to new node.
           currNode.setNext(newNode);
           //Increment item count
           this.itemCount++;
           return true;
       }
   }

   @Override
   public boolean add(int index, int value) throws IndexOutOfBoundsException {
       //Check the validity of index.
       if(index < 0 || index > itemCount)
           throw new IndexOutOfBoundsException("The specified index (" + index + ") is not not valid. Index should be between 0 and " + this.itemCount);
       else if(0 == index){ //Add new value as the first (head) element
           IntegerNode newNode = new IntegerNode(value);
           //Update the next node of new node as the current head node
           newNode.setNext(this.head);
           //Update the head to point to this node
           this.head = newNode;
           //Increment item count
           this.itemCount++;
           return true;
       }
       else {
           IntegerNode newNode = new IntegerNode(value);
           //Find the node at location index-1
           IntegerNode currNode = this.head;
           for(int i=1; i<index; i++) //Note here i goes from 1 to index-1
               currNode = currNode.getNext();
           //Update the new node to point to the next node of the current node.
           newNode.setNext(currNode.getNext());
           //Update the current node to point to the new node.
           currNode.setNext(newNode);
           //Increment item count
           this.itemCount++;
           return true;
       }
   }

   @Override
   public boolean remove(int value) {
       //TODO: Implement this method
       /***********Dummy Implementation***********/
       return false;
   }

   @Override
   public int removeAt(int index) throws IndexOutOfBoundsException {
       //Check the validity of index.
       if( index < 0 || index >= this.itemCount)
           throw new IndexOutOfBoundsException("The specified index (" + index + ") is not present in the list. Number of items present in the list is " + this.itemCount);
       //TODO: Complete this method.
       /***********Dummy Implementation***********/
       return 0;
   }

   @Override
   public int get(int index) throws IndexOutOfBoundsException {
       //Check the validity of index.
       if( index < 0 || index >= this.itemCount)
           throw new IndexOutOfBoundsException("The specified index (" + index + ") is not present in the list. Number of items present in the list is " + this.itemCount);
       //Get the Node at the index.
       IntegerNode currNode = this.head;
       for(int i=0; i<index; i++) //Note here i goes from 0 to index-1
           currNode = currNode.getNext();
       //return the value of the node.
       return currNode.getValue();
   }

   @Override
   public boolean set(int index, int value) throws IndexOutOfBoundsException {
       //TODO: Implement this method
       /***********Dummy Implementation***********/
       return false;
   }

   @Override
   public int indexOf(int value) {
       //TODO: Implement this method
       /***********Dummy Implementation***********/
       return -1;
   }

   @Override
   public boolean contains(int value) {
       //Search using the indexOf method.
       if(this.indexOf(value) >= 0)
           return true;
       //Item not found.
       return false;
   }

   @Override
   public int size() {
       return this.itemCount;
   }

   @Override
   public void clear() {
       this.head = null;
       this.itemCount = 0;
   }

   @Override
   public String toString() {
       if(null == this.head || 0 == this.itemCount)
           return "List is empty!";
       String retVal = "List Items (Count: " + this.itemCount + "): ";
       IntegerNode currNode = this.head;
       while(null != currNode) {
           retVal += currNode.getValue() + ", ";
           currNode = currNode.getNext();
       }
       return retVal.substring(0, retVal.length()-2);
   }
}
r

import java.util.Scanner;

public class SimpleIntegerListTester {

   public static void main(String[] args) {
       SimpleIntegerListADT myList = null;
       System.out.println("Select the implementation type.\n\t1 for ArrayBasedIntegerList.\n\t2 for GrowingArrayBasedIntegerList.\n\t3 for LinkedIntegerList.");
       Scanner myScanner = new Scanner(System.in);
       int option = myScanner.nextInt();
       myScanner.close();
       switch(option) {
       case 3:
           myList = new LinkedIntegerList();
           break;
       case 2:
           myList = new GrowingArrayBasedIntegerList();
           break;
       case 1:
       default:
           myList = new ArrayBasedIntegerList();
       }
      
       System.out.println(myList);
       for(int i=2; i<8; i+=2)
           myList.add(i);
       System.out.println(myList);
       myList.add(1, 10);
       System.out.println(myList);
       myList.add(66);
       System.out.println(myList);
       myList.add(44);
       System.out.println(myList);
      
       myList.remove(66);
       System.out.println(myList);
       myList.remove(4);
       System.out.println(myList);
       myList.remove(2);
       System.out.println(myList);
      
       myList.add(0, 44);
       System.out.println(myList);
      
       myList.add(3, 22);
       System.out.println(myList);
      
       myList.add(4, 33);
       System.out.println(myList);
      
       myList.add(5, 55);
       System.out.println(myList);
      
       myList.add(2, 55);
       System.out.println(myList);
      
       System.out.println(myList.contains(44));
       System.out.println(myList.indexOf(44));
       System.out.println(myList.contains(10));
       System.out.println(myList.indexOf(10));
       System.out.println(myList.contains(33));
       System.out.println(myList.indexOf(33));
       System.out.println(myList.contains(11));
       System.out.println(myList.indexOf(11));
      
   }

}

Solutions

Expert Solution

public class LinkedIntegerList implements SimpleIntegerListADT {

    //Instance variables
    private IntegerNode head;
    private int itemCount;
 
    /**
    * Default constructor.
    */
    public LinkedIntegerList() {
        super();
        this.head = null;
        this.itemCount = 0;
    }
 
    @Override
    public boolean add(int value) {
        IntegerNode newNode = new IntegerNode(value);
        if(null == this.head) { //Adding to empty list
            this.head = newNode; //Set new node as head
            this.itemCount = 1; //Set item count to 1
            return true;
        }
        else {
            //Find the last node.
            IntegerNode currNode = this.head;
            //Last node does not have a next node (null). Therefore, update the currNode to current nodes' next while it is not null.
            while(null != currNode.getNext())
                currNode = currNode.getNext();
            //Set next of last node to new node.
            currNode.setNext(newNode);
            //Increment item count
            this.itemCount++;
            return true;
        }
    }
 
    @Override
    public boolean add(int index, int value) throws IndexOutOfBoundsException {
        //Check the validity of index.
        if(index < 0 || index > itemCount)
            throw new IndexOutOfBoundsException("The specified index (" + index + ") is not not valid. Index should be between 0 and " + this.itemCount);
        else if(0 == index){ //Add new value as the first (head) element
            IntegerNode newNode = new IntegerNode(value);
            //Update the next node of new node as the current head node
            newNode.setNext(this.head);
            //Update the head to point to this node
            this.head = newNode;
            //Increment item count
            this.itemCount++;
            return true;
        }
        else {
            IntegerNode newNode = new IntegerNode(value);
            //Find the node at location index-1
            IntegerNode currNode = this.head;
            for(int i=1; i<index; i++) //Note here i goes from 1 to index-1
                currNode = currNode.getNext();
            //Update the new node to point to the next node of the current node.
            newNode.setNext(currNode.getNext());
            //Update the current node to point to the new node.
            currNode.setNext(newNode);
            //Increment item count
            this.itemCount++;
            return true;
        }
    }
 
    @Override
    public boolean remove(int value) {
        
        IntegerNode current = this.head;

        if(current.getValue() == value){
            head = current.getNext();
            this.itemCount--;
            return true;
        }

        while(current.getNext()!=null){
            IntegerNode next = current.getNext();
            if(next.getValue() == value){
                current.setNext(next.getNext());
                this.itemCount--;
                return true;
            }
            current = current.getNext();
        }
        return false;
    }
 
    @Override
    public int removeAt(int index) throws IndexOutOfBoundsException {
        //Check the validity of index.
        if( index < 0 || index >= this.itemCount)
            throw new IndexOutOfBoundsException("The specified index (" + index + ") is not present in the list. Number of items present in the list is " + this.itemCount);
        
        if(index == 0){
            IntegerNode toRemove = head;
            head = head.getNext();
            this.itemCount--;
            return toRemove.getValue();
        }
        IntegerNode curr = this.head;
            for(int i=0;i<index-1;i++){
                curr = curr.getNext();
        }
        IntegerNode toRemove = curr.getNext();
        curr.setNext(toRemove.getNext());
        this.itemCount--;
        return toRemove.getValue();
        
    }
 
    @Override
    public int get(int index) throws IndexOutOfBoundsException {
        //Check the validity of index.
        if( index < 0 || index >= this.itemCount)
            throw new IndexOutOfBoundsException("The specified index (" + index + ") is not present in the list. Number of items present in the list is " + this.itemCount);
        //Get the Node at the index.
        IntegerNode currNode = this.head;
        for(int i=0; i<index; i++) //Note here i goes from 0 to index-1
            currNode = currNode.getNext();
        //return the value of the node.
        return currNode.getValue();
    }
 
    @Override
    public boolean set(int index, int value) throws IndexOutOfBoundsException {
       //Check the validity of index.
        if( index < 0 || index >= this.itemCount)
            throw new IndexOutOfBoundsException("The specified index (" + index + ") is not present in the list. Number of items present in the list is " + this.itemCount);
           
        
        IntegerNode curr = head;
        for(int i=0;i<index;i++){
            curr = curr.getNext();
        }
        curr.setValue(value);
        return true;
    }
 
    @Override
    public int indexOf(int value) {
       
        IntegerNode curr = head;
        int index = 0;
        while(curr != null){
            if(curr.getValue() == value){
                return index;
            }
            curr = curr.getNext();
            index++;
        }
        return -1;
    }
 
    @Override
    public boolean contains(int value) {
        //Search using the indexOf method.
        if(this.indexOf(value) >= 0)
            return true;
        //Item not found.
        return false;
    }
 
    @Override
    public int size() {
        return this.itemCount;
    }
 
    @Override
    public void clear() {
        this.head = null;
        this.itemCount = 0;
    }
 
    @Override
    public String toString() {
        if(null == this.head || 0 == this.itemCount)
            return "List is empty!";
        String retVal = "List Items (Count: " + this.itemCount + "): ";
        IntegerNode currNode = this.head;
        while(null != currNode) {
            retVal += currNode.getValue() + ", ";
            currNode = currNode.getNext();
        }
        return retVal.substring(0, retVal.length()-2);
    }
 }

The completed LinkedIntegerList class is given above. The code has been run against the tester code given and runs fine. I will be glad to resolve any queries in the comments.

Please consider dropping an upvote to help a struggling college student :)

Happy Coding !!


Related Solutions

Can you make this singular linked list to doubly linked list Create a Doubly Linked List....
Can you make this singular linked list to doubly linked list Create a Doubly Linked List. Use this to create a Sorted Linked List, Use this to create a prioritized list by use. Bring to front those links recently queried. -----link.h------ #ifndef LINK_H #define LINK_H struct Link{ int data; Link *lnkNxt; }; #endif /* LINK_H */ ----main.cpp---- //System Level Libraries #include <iostream> //I/O Library using namespace std; //Libraries compiled under std #include"Link.h" //Global Constants - Science/Math Related //Conversions, Higher Dimensions...
8.13 LAB: Warm up: Contacts You will be building a linked list. Make sure to keep...
8.13 LAB: Warm up: Contacts You will be building a linked list. Make sure to keep track of both the head and tail nodes. (1) Create three files to submit. ContactNode.h - Class declaration ContactNode.cpp - Class definition main.cpp - main() function (2) Build the ContactNode class per the following specifications: Parameterized constructor. Parameters are name followed by phone number. Public member functions InsertAfter() (2 pts) GetName() - Accessor (1 pt) GetPhoneNumber - Accessor (1 pt) GetNext() - Accessor (1...
C++ Only Please 10.15 LAB: Warm up: Contacts You will be building a linked list. Make...
C++ Only Please 10.15 LAB: Warm up: Contacts You will be building a linked list. Make sure to keep track of both the head and tail nodes. (1) Create three files to submit. ContactNode.h - Class declaration ContactNode.cpp - Class definition main.cpp - main() function (2) Build the ContactNode class per the following specifications: Parameterized constructor. Parameters are name followed by phone number. Public member functions InsertAfter() (2 pts) GetName() - Accessor (1 pt) GetPhoneNumber - Accessor (1 pt) GetNext()...
implementing linked list using c++ Develop an algorithm to implement an employee list with employee ID,...
implementing linked list using c++ Develop an algorithm to implement an employee list with employee ID, name, designation and department using linked list and perform the following operations on the list. Add employee details based on department Remove employee details based on ID if found, otherwise display appropriate message Display employee details Count the number of employees in each department
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you will implement the functionality of a stack and a queue using a linked list. Your program must use of the declaration of the Stack and Queue class in Stack.h and Queue.h You have to implement the functionalities of queue (enq, deq, displayQueue) in a file called Queue.cpp. All the functions in Queue.cpp should follow the prototypes declared in Queue.h. Your code should make use...
Create a generic Linked List that does NOT use the Java library linked list. Make sure...
Create a generic Linked List that does NOT use the Java library linked list. Make sure it contains or access a subclass named Node (also Generic). And has the methods: addFirst(), addLast(), add(), removeFirst(), removeLast() and getHead(). In a separate Java class provide a main that creates an instance of your LinkedList class that creates an instance of your LinkedList that contains String types. Add the five names (you pick them) to the list and then iterate through the list...
You will be building a linked list. Make sure to keep track of both the head...
You will be building a linked list. Make sure to keep track of both the head and tail nodes. (1) Create three files to submit. PlaylistNode.h - Class declaration PlaylistNode.cpp - Class definition main.cpp - main() function Build the PlaylistNode class per the following specifications. Note: Some functions can initially be function stubs (empty functions), to be completed in later steps. Default constructor (1 pt) Parameterized constructor (1 pt) Public member functions InsertAfter() - Mutator (1 pt) SetNext() - Mutator...
c++   In this lab you will create a program to make a list of conference sessions...
c++   In this lab you will create a program to make a list of conference sessions you want to attend. (List can be of anything...) You can hard code 10 Sessions in the beginning of your main program. For example, I have session UK1("Descaling agile",    "Gojko Adzic",       60);        session UK2("Theory of constraints", "Pawel Kaminski", 90); and then:        List l;        l.add(&UK1);        l.add(&UK2); Your Session struct should have the following member data: The Title The Speaker The session...
In C++ In this lab we will creating two linked list classes: one that is a...
In C++ In this lab we will creating two linked list classes: one that is a singly linked list, and another that is a doubly linked list ( This will be good practice for your next homework assignment where you will build your own string class using arrays and linked list ) . These LinkedList classes should both be generic classes. and should contain the following methods: Print Add - Adds element to the end of the linked list. IsEmpty...
In Java In this lab we will creating two linked list classes: one that is a...
In Java In this lab we will creating two linked list classes: one that is a singly linked list, and another that is a doubly linked list ( This will be good practice for your next homework assignment where you will build your own string class using arrays and linked list ) . These LinkedList classes should both be generic classes. and should contain the following methods: Print Add - Adds element to the end of the linked list. IsEmpty...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT