X992: Swap Top Two Nodes in Stack

Use this interface definition to solve this problem.

public interface StackADT<E> { // Stack class ADT
  /* Clears the stack. */
  public void clear();

  /* Pushes argument it onto the stack. */
  public boolean push(E it);

  /* Pop and return the value at the top of the stack. */
  public E pop();

  /* Returns the value at the top of the stack. */
  public E topValue();

  /* Returns the number of elements stored in the stack. */
  public int numElements();

  /* Returns true if the stack is empty, false otherwise. */
  public boolean isEmpty();
}

Write a method to swap the top two elements of the stack. If the stack has less than 2 values, then do nothing. Otherwise, modify the stack by swapping the top two elements. The figure below shows an example of what this method should do.

Worth noting:

  • Do not just create a new stack with these letters, actually modify the one passed as an argument.
  • You don't know if the stack is implemented with nodes or arrays so you must use the interface definition to modify the stack.
  • Don't forget to check for special case (less than 2 elements).

Your Answer:

Feedback

Your feedback will appear here when you check your answer.