java-如何在使用链表实现的堆栈中实现pop操作?

java-如何在使用链表实现的堆栈中实现pop操作?,java,Java,我目前正在使用Java完成一个测试模块,该模块涉及使用链表实现堆栈 我已经实现了push()操作,但是对于pop()操作,我没有得到正确的结果。 我尝试了以下方法: public class LLStack implements LLStackQInterface{ SintNode head = new SintNode(0); @Override public void push(int num) { head.nextNode = new SintNode(num); head = he

我目前正在使用Java完成一个测试模块,该模块涉及使用链表实现堆栈

我已经实现了push()操作,但是对于pop()操作,我没有得到正确的结果。 我尝试了以下方法:

public class LLStack implements LLStackQInterface{
SintNode head = new SintNode(0);
@Override
public void push(int num) {

head.nextNode = new SintNode(num);
head = head.nextNode;
}

@Override
public int pop() {

    SintNode t = head;
    while(t.nextNode!=null)
    {
        t=t.nextNode;

    }
    t = null;
    return 0;

}
我必须推出最新的元素,所以我使用t指针导航到列表中的最后一个元素,但我没有得到结果

我确实得到了这样的结果:

输入失败:按1按3弹出按4按6
弹出式按钮8弹出式按钮9弹出式按钮
预期输出为:8->4->1->NULL

代码生成的实际输出:9->8->6->4->3->1->NULL


我设法扭转了列表,但显然我的pop()不起作用。我该怎么办?

您的
pop
push
方法都有漏洞

您在
push
中对下一个指针的管理不正确。首先将当前头部的下一个指针设置为新节点,然后将新节点指定给头部。因此,
head.next==null
。正确的方法是:

公共无效推送(int num){
SintNode n=新的SintNode(num);
n、 下一个=头部;
水头=n;
}
这样,您可以在列表的前面插入新节点,并保持指向下一个元素的指针,即列表的前一个标题

在pop方法中,遍历到列表的末尾。这是不正确的,因为您将元素添加到列表的前面。堆栈是后进先出(LIFO)数据结构,这意味着您应该删除插入的最后一个元素。在本例中,它是列表的标题

public int-pop(){
if(head==null)
返回0;
节点t=头部;
头=t.next;
t=零;
返回0;
}
在这里,我们首先将新的
头设置为
头。接下来
,然后删除当前的


我运行了正确的版本,实际输出与预期输出匹配。

您的预期输出正确吗?我认为这是错误的。。。首先
pop
将给出
3
而不是
9
这就是你的整个推送方法吗?我觉得不太对。在插入新节点之前,是否需要临时节点来存储当前磁头。此外,@ZainArshad在操作完成后,其预期堆栈为8->4->1done@wakeel我的push()方法工作得很好,但我不知道这是否是正确的实现。好的,所以它应该打印堆栈的最后状态,是的
push()
根本不正确。它没有指向最新的元素added@ZainArshad你能(通过回答或评论)纠正我的代码吗?在
pop()
中,你可以只写
head=head。下一步
。。。kaaboom完成了。是的,您也可以这样做,但通常最好将
null
指定给要删除的内容。谢谢您的回答。但是,当预期答案为空时,我确实会收到NullPointException错误。请在pop方法中添加对
NULL
的检查。@quetzalcatl垃圾收集器将处理此问题。。。因为引用计数将变为零。然而,正如你所说,这是好的,就让它去吧
@Override public void push(int num) {
    // store a copy of the current head
    SintNode temp = this.head;

    // update the current head to the pushed value
    this.head = new SintNode(num);

    // link the head to the rest of the stack, as each subsequent node will point to another one until the tail
    this.head.nextNode = temp; }

@Override public int pop() {
    // assuming SintNode has a value property
    int value = this.head.value;

    // remove this node by overwriting it as the next
    this.head = this.head.nextNode;

    // the value of removed node
    return value; }