简体   繁体   中英

Reverse method for List in Java prints the List Twice

For the exam, I train to write the some algorithms to the final exam. One of them is creating the reverse() method, which reverses the List<>. The problem that my method prints the list twice. How can I change the method?

Here, the code of the List.java file. The methods removeFromBack(), removeFromFront(), insertAtBack(), insertAtFront(), print(), isEmpty(), the classes List and ListNode are already defined in Deitel's Java book:

   public void reverse()
   {
      if ( isEmpty() ) 
      {
         return;
      } // end if
      ListNode< T > current = firstNode;

      // while not at end of list
      while ( current != null)
      {
          insertAtFront(current.data);
          current = current.nextNode;
      }  // end while


   }

I have found such a solution:

  public void reverse() {
      int size = 0;
      if (isEmpty()) {
          return;
      } // end if
      ListNode < T > current = firstNode;

      while (current != null) {
          current = current.nextNode;
          size++;
      }

      current = firstNode;

      // while not at end of list
      while (size != 0) {
          insertAtFront(current.data);
          current.data = null;
          current = current.nextNode;
          size--;
      }

      current = firstNode;

      while (lastNode.data == null) {
          removeFromBack();
      }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM