堆栈推送方法无限循环Java

时间:2015-11-28 20:22:57

标签: java stack infinite-loop singly-linked-list

我不明白为什么printList()在被调用时无限循环。我正在尝试编写堆栈链接列表并打印列表而不使用java中的内置堆栈方法。为什么我的print方法无限循环,如何解决这个问题呢?

public class LinkedListStack{
    private String item;
    private Node next;
    private Node top = null;

    public LinkedListStack(){
    }

    public void push(String item){
        top = new Node(item, top);
    }

    public void printList(){
        Node currentNode = top;
        for(currentNode = top; currentNode.getItem()!= null; currentNode = currentNode.getNext()){
            System.out.println(currentNode.getItem());
        }
    }

    public class Node{
        public Node(String newItem, Node nextNode){
            item = newItem;
            next = nextNode;
        }

        public Node(String newItem){
            item = newItem;
            next = null;
        }

        //to set the value of the next field
        public void setNext(Node nextNode){
            next = nextNode;
        }

        //read the value of the next field
        public Node getNext(){
            return(next);
        }

        //to set the value of the item field
        public String setItem(String newItem){
            item = newItem;
            return(item);
        }

        //read the value of the item field
        public String getItem(){
            return(item);
        }
    }

    public static void main(String args[]){
        LinkedListStack newList = new LinkedListStack();
        newList.push("hello");
        newList.push("goodbye");
        newList.printList();
    }
}

1 个答案:

答案 0 :(得分:1)

问题是nextLinkedListStackNode的字段,并在所有Node个实例之间共享。当您创建另一个Node并设置项目时,您将更改所有节点。要修复它,只需将字段声明移动到printList内部类。 除此之外,public class LinkedListStack { private Node top = null; public LinkedListStack() { } public void push(final String item) { top = new Node(item, top); } public void printList() { Node currentNode = top; for (currentNode = top; currentNode != null; currentNode = currentNode.getNext()) { System.out.println(currentNode.getItem()); } } public class Node { private String item; private Node next; public Node(final String newItem, final Node nextNode) { item = newItem; next = nextNode; } public Node(final String newItem) { item = newItem; next = null; } // to set the value of the next field public void setNext(final Node nextNode) { next = nextNode; } // read the value of the next field public Node getNext() { return next; } // to set the value of the item field public String setItem(final String newItem) { item = newItem; return item; } // read the value of the item field public String getItem() { return item; } } public static void main(final String args[]) { final LinkedListStack newList = new LinkedListStack(); newList.push("hello"); newList.push("goodbye"); newList.printList(); } } 方法中的循环条件是错误的:下一个节点为空,而不是其项。 这是一个有效的例子:

url: "cuisine/{name}"