-1
我不明白爲什麼printList()在調用時無限循環。我試圖編寫一個堆棧鏈表並打印列表,而不使用java中的內置堆棧方法。爲什麼我的打印方法無限循環,我該如何糾正這個問題?堆棧推送方法無限循環Java
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();
}
}
爲什麼你在循環之前申報的printList「currentNode」(),如果你要創建一個本地變量,在環頭相同的名稱? – Shondeslitch
您是否嘗試過調試? – meriton