【发布时间】:2017-04-07 07:58:17
【问题描述】:
问题:
我无法第二次弹出该元素。 例如,我有 4,3,2,1,堆栈顶部有 4。我无法删除 3,2
谁能指导我为什么?
下面是堆栈实现:
public static void push(int data){
if(head==null){
Node newNode=new Node(data);
head=newNode;
}else{
Node newNode1=new Node(data);
newNode1.next=head;
head=newNode1;
}
}
public static int pop(){
if(head==null){
return 0;
}
else{
Node temp=head;
int a=temp.data;
temp=null;
return a;
}
}
public static void traverse(){
Node temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
【问题讨论】:
-
您是否期望
temp=null;对列表实际执行任何操作? -
您以
temp.data的身份访问了head并返回该值。但是您没有对head做更多的事情... * pshh,将temp.next()分配给head * -
你错过了
head = temp.next,它将把你的头移到下一个并删除/删除前一个。 -
@user2357112 想要在堆栈顶部作为空节点。
标签: java linked-list stack