本文介绍了我在我的代码中得到nullpointerexception ..不知道该代码中有什么错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到Null指针异常...不知道该代码中有什么错误...如何解决它。
我是什么尝试过:
I am getting Null pointer exception...don't know whats wrong in that code...how to resolve it.
What I have tried:
import java.util.Scanner;
class Node
{
private int data;
private Node next;
public Node(int d , Node n)
{
data = d;
next = n;
}
public void setData(int d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public int getData()
{
return(data);
}
public Node getNext()
{
return(next);
}
}
class Linkedlist
{
private int size;
private Node start;
public Linkedlist()
{
size = 0;
start = null;
}
public void insetAtfirst(int val)
{
Node n = new Node(val,start);
n.setData(val);
n.setNext(start);
start = n;
size++;
}
public void viewlist()
{
Node t;
t = start;
for(int i=1;i<=size;i++)
{
System.out.println(" " + t.getData());
t = t.getNext();
}
}
public void deleteAltNode()
{
Node t1;
t1 = start;
for(int i=1;i<=size;i++)
{
System.out.println(" " + t1.getData());
t1 = t1.getNext().getNext();
}
size--;
}
}
public class Delete_alternate_node
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Linkedlist l = new Linkedlist();
System.out.println("Enter the no of node ");
int k = sc.nextInt();
for(int i=1;i<=k;i++)
{
System.out.println("Enter the elements for linkedlist");
int val = sc.nextInt();
l.insetAtfirst(val);
}
System.out.println();
l.viewlist();
System.out.println();
l.deleteAltNode();
}
}
推荐答案
import java.util.Scanner;
class Node
{
private int data;
private Node next;
public Node(int d , Node n)
{
data = d;
next = n;
}
public void setData(int d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public int getData()
{
return(data);
}
public Node getNext()
{
return(next);
}
}
class Linkedlist
{
private int size;
private Node start;
public Linkedlist()
{
size = 0;
start = null;
}
public void insertAtfirst(int val)
{
Node n = new Node(val,start);
n.setData(val);
n.setNext(start);
start = n;
size++;
}
public void viewlist()
{
Node t;
t = start;
while ( t != null )
{
System.out.print(" " + t.getData());
t = t.getNext();
}
System.out.println();
}
public void deleteAltNode()
{
Node node;
node = start;
while ( node != null )
{
Node next = node.getNext();
if ( next != null)
{
node.setNext (next.getNext());
--size;
}
node = node.getNext();
}
}
}
public class Delete_alternate_node
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Linkedlist l = new Linkedlist();
System.out.println("Enter the no of node ");
int k = sc.nextInt();
for(int i=1;i<=k;i++)
{
System.out.println("Enter the elements for linkedlist");
int val = sc.nextInt();
l.insertAtfirst(val);
}
System.out.print("list before alternate nodes deletion: ");
l.viewlist();
System.out.print("list after alternate nodes deletion: ");
l.deleteAltNode();
l.viewlist();
}
}
这篇关于我在我的代码中得到nullpointerexception ..不知道该代码中有什么错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!