我无法通过stack
:
single linked list
这是我正在实施的界面:
public interface Stack<E> {
/**
* element at the top without removing it
*/
public E peek();
/**
* pop from the stack
*/
public void pop();
/**
* insert into the stack
*/
public void push( E e );
/**
* isEmpty
*/
public boolean isEmpty();
/**
* size
*/
public int size();
/**
* reverse
*/
public Stack<E> reverse();
}
这是我的实施:
public class ListStack<E> implements Stack<E> {
private static class Node<T> {
private T item;
private Node<T> next;
private Node(T item, Node<T> next) {
this.item = item;
this.next = next;
}
}
private Node<E> first;
private int size;
public ListStack() {
this.size = 0;
this.first = null;
}
@Override
public E peek() {
return first.item;
}
@Override
public void pop() {
first = first.next;
size--;
}
@Override
public void push(E e) {
Node<E> node = new Node<E>(e, first);
first = node;
size++;
}
@Override
public boolean isEmpty() {
return (first == null);
}
@Override
public int size() {
return size;
}
@Override
public Stack<E> reverse() {
}
}
我正在努力使用reverse
方法,而且我不确定我是否正确编程。
非常感谢任何帮助!
答案 0 :(得分:1)
要反转现有堆栈,您只需要遵循现有堆栈的Node.next引用,并在整个过程中推送新堆栈上的项目。
@Override
public Stack<E> reverse()
{
ListStack<E> reversed = new ListStack<E>();
Node<E> node = first;
while(node != null)
{
reversed.push(node.item);
node = node.next;
}
return reversed;
}