Implement a method transfer in class LinkedStack. This method should transfer all elements of a stack sourceS to another stack targetS so that the element that starts at the top of sourceS is the first one to be inserted in targetS, and the element at the bottom of sourceS ends up at the top of targetS. The operation should result in sourceS being an empty stack. Test this method in the main method of LinkedStack.
Implement a method transfer in class LinkedStack. This method should transfer all elements of a stack sourceS to another stack targetS so that the element that starts at the top of sourceS is the first one to be inserted in targetS, and the element at the bottom of sourceS ends up at the top of targetS. The operation should result in sourceS being an empty stack. Test this method in the main method of LinkedStack.
package stacks;
public class LinkedStack<E> implements Stack<E> {
/** The primary storage for elements of the stack */
private SinglyLinkedList<E> list = new SinglyLinkedList<>(); // an empty list
/** Constructs an initially empty stack. */
public LinkedStack() { } // new stack relies on the initially empty list
@Override
public int size() { return list.size(); }
@Override
public boolean isEmpty() { return list.isEmpty(); }
@Override
public void push(E element) { list.addFirst(element); }
@Override
public E top() { return list.first(); }
@Override
public E pop() { return list.removeFirst(); }
public String toString() {
return list.toString();
}
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images