I am trying to write a peek method for a header linked list class. However, it doesn’t return the first value.
public E peek () throws NoSuchElementException {
ListNode<E> temp = highest;
ListNode<E> r = temp;
if (temp.next == null) throw new NoSuchElementException();
else r.next = temp.next.next;
return r.next.value;
}
I understand why it doesn’t return the first value. Because in my code else r.next will already point to the next node in the list. So for 5,4,3,2,1 it will return 4 on the first call instead of 5. temp is pointing to the highest node which is the header node. How can I get the method to return the first value in the list, 5, first?
A good way to implement Linked list is that
headershould always be empty node in the list soit should not hold a value. This way when you callnexton header you actually go to first element only.header http://easy2teach.net/wp-content/uploads/2011/06/header-linked-list.jpg
As depicted in above digram as header next is actually the first element of the Linked List
So you Peek operation is not supposed to throw
NoSuchElementExceptioninstead it should returnnullso simple method can be