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 NodeE e Node n
elemente;
next n;
public E getElementreturn elements;
public Node getNextreturn next;
public void setNextNode nnextn;
instance variables of the CircularlyLinkedList
private Node tailnull; we store tail but not head
private int size; number of nodes in the list
public CircularlyLinkedListconstructs an initially empty list
access methods
public int sizereturn size;
public Boolean isEmptyreturn size;
public E firstreturns but does not remove the first element
If isEmpty return null;
return tail.getNextgetElement; the head is after the tail
public E lastreturns but does not remove the last element
If isEmpty return null;
return tail.getElement;
public void rotaterotate the first element to the back of the list
If tail nullif empty, do nothing
tailtail.getNext; the old head becomes the new tail
public void addFirst E eadds element e to the front of the list
If size
tail new Nodee null;
tail.setNexttail; link to itself circularly
else
Node newestnew Nodee tail.getNext;
tail.setNextnewest;
size;
public void addLastE eadds element e to the end of the list
addFirste; insert new element at front of list
tailtail.getNext; now new element becomes the tail
public E removeFirstremoves and returns the first element
If isEmpty return null; nothing to remove
Node head tail.getNext;
If headtail tail null; must be the only node left
else tail.setNextheadgetNext; 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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
