Question
How to write a method to find the Nth to last item in a singly linked list . The list does not know nor provide
How to write a method to find the Nth to last item in a singly linked list. The list does not know nor provide a method to return its size.
How do I implement a generic linked list that is only singly linked. That is, each node only knows about the next node. Naming it SinglyLinkedList. The linked list will have a head and a tail node which contain no data. It will not keep track of its size. It will implement the Iterable
The linked list must provide the following methods:
public void add(AnyType element) public void remove(AnyType element)
public void clear() public AnyType getNthToLast(int n) public SinglyLinkedListIterator iterator()
The method add() adds the new element to the end of the list. The method remove() removes the first Node from the list that contains element. clear() removes all elements from the list. getNthToLast() returns the Nth to last element in the list. For example, in the list of numbers 5 4 3 2 1, 2 is the 2nd to last element, 3 is the 3rd to last, and so on. iterator() returns an instance of the SinglyLinkedListIterator.
SinglyLinkedListIterator must implement the following 4 methods.
public boolean hasNext() public AnyType next() public void remove() public void add(AnyType element)
hasNext() returns true if there is a next element in the list, and false otherwise. next() moves the iterator to point to the next Node in the list and returns the element held by that node. If next() is called and there is no next element, next() must throw a NoSuchElementException. The iterators remove() removes from the list the node currently pointed to by the Iterator (This is the element last returned by next()). If a call to remove() attempts to remove the tail, remove() must throw an IllegalStateException. Likewise, the iterators method add() adds the new element to the list after the node the iterator currently points to.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started