问题:
我无法第二次弹出元素。例如,我有 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;
}
}
你的 pop 方法有问题
public static int pop(){
if(head==null){
return 0;
}
else{
Node temp=head;
head = head.next;
int a=temp.data;
temp=null;
return a;
}
}
你忘了把头移到下一个节点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句