面对问题中的空指针异常[重复]

问题描述 投票:-2回答:1

我在此代码中面临空指针异常:

import java.util.*;
import java.io.*;
import java.lang.*;


class Node
{
    int data;
    Node next;
    Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}

class Driver
{
    static Node insertNode(Node head, int x)
    {
        Node node = new Node(x);
        if(head == null)
            return new Node(x);

        Node temp = head;
        while(temp.next != null)
            temp = temp.next;

        temp.next = node;

        return head;
    }
    public static void main(String args[])throws IOException
    {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(read.readLine());

        while(t-- > 0)
        {
            int n = Integer.parseInt(read.readLine());

            String str[] = read.readLine().trim().split(" ");
            Node head = null;
            for(int i = 0; i < n; i++)
                head = insertNode(head, Integer.parseInt(str[i]));

            int node = Integer.parseInt(read.readLine());

            System.out.println(new Get().searchLinkedList(head, node) ? "1" : "0");
        }
    }
}

仅修改这部分代码:

class Get
{
    public static boolean searchLinkedList(Node head, int x)
    {
        // Your code here
        if(head==null)
            return false;
        Node first=head;
        Node second=first.next;
        while(first!=null || second!=null){
            if((first.data==x) || (second.data==x))
                return true;
            first=second.next;
            second=first.next;
        }
        return false;
    }
}

错误是:运行时错误:

Runtime ErrorException in thread "main" java.lang.NullPointerException
    at Get.searchLinkedList(File.java:77)
    at Driver.main(File.java:53)

有人可以通过示例示例告诉我此异常背后的原因,我一直在尝试自己执行此操作,但我在这里看不到任何问题。问题是,我有两个引用,第一个和第二个,它们都通过分别跳过一个节点来遍历,看看元素x是否存在,如果是,则返回true,否则返回false。

如果可能,用相同的逻辑纠正问题。

java linked-list
1个回答
1
投票

我想我找到了此空指针异常背后的原因。让我告诉你一个空想。假设我们的LinkedList中只有头一个节点。因此,我们的第一个将指向head,第二个为null。现在我们将进入while循环,因为只有or条件,而我们的第一个不为null,因此我们将进入循环。然后假设first.data!= x,然后将检查second.data == x,它基本上是null.data == x。这件事会给你空指针异常。

    Node first=head;
    Node second=first.next;
    while(first!=null || second!=null){
        if((first.data==x) || (second.data==x))
            return true;
        first=second.next;
        second=first.next;

您可以简单地搜索一个节点,例如:

    Node first=head;
    while(first!=null){
        if(first.data==x)
            return true;
        first=first.next;

如果要跳过节点,则需要处理不同的边缘情况。让我知道您要达到的目标,我会帮助您编写代码。

© www.soinside.com 2019 - 2024. All rights reserved.