【问题标题】:Why I am not able to Pop Element from stack using Linked List Implementation?为什么我不能使用链表实现从堆栈中弹出元素?
【发布时间】: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


【解决方案1】:

你的 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;
    }
}

你忘了把头移到下一个节点。

【讨论】:

    【解决方案2】:

    您并没有从列表中删除元素,您只是将指向 head 的变量设为 Null。这不会改变linkedList。

    你有两个选择:

    1. 使用链接列表中的内置函数从列表中删除元素。
    2. 更改 list.head 并使其指向下一个元素。

    在情况 2 中,你必须在 pop 方法上添加以下内容:

     head = head.next;
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2014-12-18
      相关资源
      最近更新 更多