我如何使用java中的printStream参数打印堆栈?

时间:2015-11-07 14:32:13

标签: java interface stack java-io printstream

这是一个接口的方法,我必须在另一个类中实现,我不知道如何创建它。我必须使用带有printStream参数的linkedList打印堆栈。在类Node(对于linkedList)中,我有一个方法getObject()。

import java.io.PrintStream;
import java.util.NoSuchElementException;

public interface StringStack {


    public boolean isEmpty();

    public void push(String item);

    public String pop() throws NoSuchElementException;

    public String peek() throws NoSuchElementException;

    /**
     * print the contents of the stack, starting from the item
         * on the top,
     * to the stream given as argument. For example, 
     * to print to the standard output you need to pass System.out as
     * an argument. E.g., 
     * printStack(System.out); 
     */
    public void printStack(PrintStream stream);

    public int size();

}




public class StringStackImpl implements StringStack {
    private Node head;
....
    public void printStack(PrintStream stream) {???}

}

1 个答案:

答案 0 :(得分:0)

不确定堆栈的结构如何,但应该这样做:

  Node node = head; // top of the stack

  while(node != null){
     stream.println(node.value);
     stream.flush();
     node = node.next;
  }