how to implement linked list in java
Linked List is a data structure ,which is basically use to store the data . Linked List is use to perform various operations like insertion and deletion at the middle position because in the linked list node concept is available so that we are not dependent to on the indexes.
In the arrays concept if we want to perform insertion and deletion at middle than we have to perform various shifting operations that will create the performance problem.
Linked list operations:
1.insert node at beginning
2.insert node at last
3.delete a node.
4.sort elements inside node.
5.display the values of nodes
Example: Let's discuss the linked list implementation and it's various operations through the java program
class Linked
{
Node head;
Linked(int item)
{
head=new Node();
head.value=item;
head.next=null;
}
public boolean insert(int item) //Insert node at beginning
{
Node n=new Node();
n.value=item;
n.next=head;
head=n;
return true;
}
public void show()// Display elements
{
Node z=head;
while(z!=null)
{
System.out.print(z.value+" ");
z=z.next;
}
}
public boolean delete(int item) linked list
{
if(head.value==item)
{
head=head.next;
return true;
}
else
{
Node x=head;
Node y=head.next;
while(true)
{
if(y==null|| y.value==item)
{
break;
}
else
{
x=y;
y=y.next;
}
}
if(y!=null)
{
x.next=y.next;
return true;
}
else{
return false;
}
}
}
public boolean insertlast(int item)
{
Node n=new Node();
Node i=head;
while(i.next!=null)
{
i=i.next;
}
n.value=item;
n.next=null;
i.next=n;
return true;
}
public void sort()
{
Node a=head.next;
int temp=0;
while(a.next!=null)
{
Node b=head.next;
while(b.next!=null)
{
if(b.value<b.next.value)
{
temp=b.value;
b.value=b.next.value;
b.next.value=temp;
}
b=b.next;
}
a=a.next;
}
}
class Node //Inner class in the Linked list ..
{
int value;
Node next;
}
}
class Test
{
public static void main(String[] args)
{
Linked l=new Linked(5);
l.insert(10);
l.insert(20);
l.insert(30);
l.insert(40);
l.show();
l.delete(20);
System.out.println(" ");
l.show();
System.out.println(" ");
l.insertlast(100);
l.show();
System.out.println(" ");
l.sort();
l.show();
}
}
F:\viren-sharma>java Test
40 30 20 10 5
40 30 10 5
40 30 10 5 100
40 100 30 10 5