Java 方法不返回链表的第一个值



我正在尝试为标头链接列表类编写一个peek方法。但是,它不会返回第一个值。

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;
}

我明白为什么它不返回第一个值。因为在我的代码中,else r.next已经指向列表中的下一个节点。因此,对于5,4,3,2,1,它将在第一个呼叫中返回4,而不是5。温度指向最高节点,即标题节点。如何获得返回列表中的第一个值的方法,第5,首先?

实现链接列表的一种好方法是, header应该始终是列表中的空节点,因此it should not hold a value。这样,当您在标题上调用next时,您实际上仅转到第一个元素。

标题http://easy2teach.net/wp-content/uploads/2011/06/header-linked-list.jpg

如上图中所示的标题下一个实际上是链接列表的第一个元素

因此,您不应该抛出NoSuchElementException的操作,而应该返回null,因此可以简单的方法

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

最新更新