如何打印链表?

时间:2014-02-05 16:54:47

标签: java linked-list tostring

如果你看下面我的toString()方法,你会发现我还没有完成它。我不知道怎么样?任何人都可以解释我如何进行?困惑: - |我是链接列表的新手,因此在我意识到当然没有任何数组之前,我自动选择了Arrays.toString()方法。

import java.util.Arrays;


public class LinkedIntegerStack {

private Node top = null;
private int size = 0;

public int size(){
    return size;
}

public boolean isEmpty() {
    if(top == null){
        return true;
    }
    else{
        return false;
    }
}

public void push(int value) {
    Node n = new Node(value);
    n.next = top;
    top = n;
    size++;
}

public int top(){ //just returns a value..doesn't change structure

    return top.element;
}

public int pop(){
    if (isEmpty()){
        throw new StackEmptyException();
    }
    int toReturn = top.element;
    top = top.next;
    size--;

    return toReturn;
}       

public String toString() {
    return "[ Top = " + size +"]" + "[Stack = " );
}

private class Node {
    int element;
    Node next;

    public Node(int value){
        element = value;
    }
}

public static void main(String[] args) throws StackEmptyException{

    LinkedIntegerStack stack = new LinkedIntegerStack();

    stack.push(17);
    System.out.println(stack);

    stack.push(11);
    System.out.println(stack);

    try{
            stack.pop();
            System.out.println(stack);
        }
    catch(StackEmptyException ex){
            System.out.print("Stack is Empty: Error");
        }
    System.out.println("Stack: " + stack);
}

}

2 个答案:

答案 0 :(得分:1)

解决方案很简单。

迭代堆栈应该足够了。

public String toString() {
    String result = "[ Top = " + size +"]" + "[Stack = [";

    if (top == null) {
        return result + "]]";

    Node temp = top;
    while (temp != null) {
        result += temp + ', '
        temp = temp.next;
    }

    return result += temp.element + "]]";
}

当然你应该至少为Node类添加getter方法,即getElement()和getNext();

PS:代码未经过测试,但应该没问题。

答案 1 :(得分:0)

System.out.println(Arrays.toString(stack.toArray()));

来自https://stackoverflow.com/a/395403/2736496

JavaDoc:Arrays。toString(o []),Collection。toArray(cll)