Robert
Robert

Reputation: 143

questions on methods of LinkedList Java

Hi I'm very new to Java and have this problem with Linked List. My find and max methods are not producing the correct output. The find method is to take a type E element as argument, and returns true if the item is in the linked List, or false otherwise. The max method is to return the maximum element in the list if the list is not empty, or null if empty list. The comparison has to be done by compareTo().

I have tried finding "Apple", which is indeed in the list, however, return false. Also the max element I got back is "Apple", instead of "Watermelon".

Any help is greatly appreciated!

  public E max(){
      Iterator<E> iterator=iterator();
      E max = iterator.next();
      while (iterator.hasNext())
      {  
         E next = iterator.next();
         if (max.compareTo(next) > 0) 
            max = next;
      }
    return max;
  }

Upvotes: 0

Views: 161

Answers (1)

Thilo
Thilo

Reputation: 262814

if (current.equals(e)){
          return true;

You need to compare to the Node's item, not the Node itself.

if (max.compareTo(next) > 0) 
        max = next;

That comparison needs to be reversed: You have found a new max if the old one is smaller than the current item.

Upvotes: 2

Related Questions