class StackNode{
int data;
StackNode next;
public StackNode(int data, StackNode next){
this.data = data;
this.next = next;
}
}
public class StackWithLinkedList {
StackNode root = null;
public void push(int data){
if(root == null)
root = new StackNode(data, null);
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
temp.next = new StackNode(data, null);
}
}
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
int data = temp.data;
temp = null;
return data;
}
}
public void print(){
StackNode temp = root;
while(temp!= null){
System.out.print(temp.data +" ");
temp = temp.next;
}
System.out.print("\n");
}
public static void main(String[] args) {
StackWithLinkedList stack = new StackWithLinkedList();
for(int i = 1; i<=15; i++){
Random randomGen = new Random();
stack.push(randomGen.nextInt(i));
}
stack.print();
System.out.print("\n");
try {
System.out.println("Deleted: "+stack.pop());
System.out.println("Deleted: "+stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
stack.print();
}
}
我想實現與鏈表的堆棧。在彈出功能我遍歷,直到最後一個節點,並使其爲空。當我打印清單。它保持不變。將根分配給temp並遍歷它會導致任何問題?從鏈接列表中刪除一個節點
你應該是最後一個前旁邊元素的空設置字段。不是元素 – Damian0o
但我把那個元素本身作爲null。不會那樣釋放內存嗎? –
你不應該對空閒內存感興趣,因爲GC會處理這個問題。你應該從列表中刪除對該元素的引用 – Damian0o