Implement Linked List in Java
I am trying to Implement a Linked List Using Java. The code I have used is
as follow
public class LinkNode
{
private int data;
public LinkNode next;
public LinkNode (int data)
{
this.data = data;
}
public void setData(int data)
{
this.data = data;
}
public int getData()
{
return this.data;
}
public void setNext(LinkNode next)
{
this.next = next;
}
public LinkNode getNext()
{
return this.next;
}
public static void main (String [] args)
{
LinkNode Head = null;
LinkNode Last = null;
LinkNode Node1 = new LinkNode(3);
LinkNode Node2 = new LinkNode(4);
LinkNode Node3 = new LinkNode(5);
Head.setNext(Node1);
Node1.setNext(Node2);
Node2.setNext(Node3);
Node3.setNext(Last);
int iCounter =0;
while (Head.getNext()!=null)
{
iCounter=iCounter+1;
Head = Head.getNext();
}
System.out.println(iCounter);
}
}
Now The problem here is I want to create a Reference Head which should
point to first node that is Node1 but shoud not have any data. So I am
Initializing a reference Head with null LinkNode Head = null; but when I
am trying to execute this code I am getting nullpointer exception. Can
anyone Please let me know how to Implement Head Reference.
Thanks in Advance
No comments:
Post a Comment