Question: Give an implementation of the size ( ) method for the following CircularlyLinkedList class assuming that we did not maintain size as an instance variable.

Give an implementation of the size() method for the following CircularlyLinkedList class assuming that we did not maintain size as an instance variable. The size () method should return a count of the number of node in the list. Hint: see chapter on Linked List
Following is the code for the CircularlyLinkedList class:
public class CircularlyLinkedList {
//-------------------nested Node class------------------
private static class Node {
private E element; //reference to the element stored at this node
private Node next; //reference to the subsequent node in the list
public Node(E, e, Node n){
element=e;
next= n;
}
public E getElement(){return elements;}
public Node getNext(){return next;}
public void setNext(Node n){next=n;}
// instance variables of the CircularlyLinkedList
private Node tail=null; //we store tail (but not head)
private int size=0; //number of nodes in the list
public CircularlyLinkedList(){}//constructs an initially empty list
//access methods
public int size(){return size;}
public Boolean isEmpty(){return size==0;}
public E first(){//returns (but does not remove) the first element
If (isEmpty()) return null;
return tail.getNext().getElement(); //the head is after the tail
}
public E last(){//returns (but does not remove) the last element
If (isEmpty()) return null;
return tail.getElement();
}
public void rotate(){//rotate the first element to the back of the list
If (tail != null)//if empty, do nothing
tail=tail.getNext(); //the old head becomes the new tail
}
public void addFirst (E e){//adds element e to the front of the list
If (size==0){
tail = new Node<>(e, null);
tail.setNext(tail); //link to itself circularly
} else {
Node newest=new Node<>(e, tail.getNext());
tail.setNext(newest);
}
size++;
}
public void addLast(E e){//adds element e to the end of the list
addFirst(e); //insert new element at front of list
tail=tail.getNext(); //now new element becomes the tail
}
public E removeFirst(){//removes and returns the first element
If (isEmpty()) return null; //nothing to remove
Node head = tail.getNext();
If (head==tail) tail = null; //must be the only node left
else tail.setNext(head.getNext()); //removes head from the list
size --;
return head.getElement();
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!