gpt4 book ai didi

java - 堆栈实现空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:29:13 25 4
gpt4 key购买 nike

这是我使用链表实现堆栈的程序。但我不断收到 java.lang.NullPointerException在第 31 行,即 pop功能。为什么会发生这种情况以及如何纠正它?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class StackImplementtionLinkedList
{
private Node first= null;

private class Node
{
String item;
Node next;
}

public boolean isEmpty()
{
return first==null;
}

public void push(String item)
{
Node old= first;
first= new Node();
first.item= item;
first.next= old;
}
public String pop()
{
String item= first.item;
first= first.next;
return item;
}
public void printStack()
{
while(first!=null)
{ System.out.println(first.item);
first= first.next;
}
}

public static void main(String[] args) throws FileNotFoundException
{
StackImplementtionLinkedList stack= new StackImplementtionLinkedList();
String filename= "myfile.txt";
File textfile= new File(filename);
Scanner input= new Scanner(textfile);
while(input.hasNextLine())
{
String line= input.nextLine();
stack.push(line);
}
input.close();
stack.printStack();
String popped= stack.pop();
System.out.println(popped+ " is the popped item.");
popped= stack.pop();
System.out.println(popped+ " is the popped item.");
stack.printStack();
}
}

最佳答案

请注意,调用 printStack() 方法后,首先为 null

我会制作一个副本,然后迭代。

public void printStack()
{
Node copy = first;
while(copy!=null)
{
System.out.println(copy.item);
copy = copy.next;
}
}

关于java - 堆栈实现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com