A linked list refers to a collection of nodes connected to each other with the help of a link. Each link object contains a reference usually called next to the next link in the list. Although an array is a common way of storing data elements, but inserting an element in between an array or deleting an element from an array requires a lot of shuffling of other array elements.
So, the better way is keep the data in terms of nodes linked to each other with the help of links. A link of one node can be set to point at another node without any reshuffling. Hence inserting or deleting an element from linked list is quite an easy task (just changing the link locations will do the job).
import java.io.*;
class node
{
public int v;
public node nxt;
public node(int x)
{
v=x;
}
public void dispval()
{
System.out.println(v);
}
}
class LinkList
{
private node first,p,q;
public LinkList()
{
first=null;
}
public void insertval(int x)
{
node p = new node(x);
p.nxt=null;
if(first==null)
{
first=p;
q=p;
}
else
{
q.nxt=p;
q=p;
}
}
public void delfirst()
{
q=first;
first=first.nxt;
q=null;
}
public void displayList()
{
node r=first;
while(r !=null)
{
r.dispval();
r=r.nxt;
}
}
}
class SinglyLinkedList
{
public static void main(String args[]) throws IOException
{
LinkList k= new LinkList();
BufferedReader b= new BufferedReader(new InputStreamReader(System.in));
String h;
int n,i,m;
System.out.println("How many numbers you want to insert in link list");
h=b.readLine();
n=Integer.parseInt(h);
System.out.println("Enter numerical in linked list");
for(i=1;i<=n;i++)
{
h=b.readLine();
m=Integer.parseInt(h);
k.insertval(m);
}
k.displayList();
}
}