user1766888
user1766888

Reputation: 409

Java method doesn't return the first value of a linked list

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?

Upvotes: 1

Views: 506

Answers (1)

Amit Deshpande
Amit Deshpande

Reputation: 19185

A good way to implement Linked list is that header should always be empty node in the list so it should not hold a value. This way when you call next on 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 NoSuchElementException instead it should return null so simple method can be

 public E peek ()
 {
   if(check element does exist using size ==0)
      return null;
   else 
      return highest.next.value;
 }

Upvotes: 1

Related Questions