Linked List Implementation In Java
import java.io.*;
class Node
{
private int element;
private Node next;
static Node head;
static Node tail;
public Node()
{
}
public Node(int e, Node n)
{
element = e;
next = n;
}
public int getElement()
{
return element;
}
public Node getNext()
{
return next;
}
public void setElement(int e)
{
element = e;
}
public void setNext(Node n)
{
next = n;
}
public void insert(int e)
{
Node n=new Node();
n.setElement(e);
n.setNext(this.getNext());
this.setNext(n);
}
public void delete(int e)
{
Node n=new Node();
Node prev = new Node();
n.setNext(head.getNext());
n = n.getNext();
if (head.getNext() != null)
{
do
{
if(n.getElement() == e)
prev.setNext(n.getNext());
prev= n;
n = n.getNext();
}
while(n.getNext()!=null);
}
}
public void display()
{
Node n=new Node();
n.setNext(head.getNext());
n = n.getNext();
if (head.getNext() != null)
{
do
{
System.out.println(n.getElement());
n = n.getNext();
}
while(n.getNext()!=null);
System.out.println(n.getElement());
}
}
}
class LinkedList
{
public static void main(String args[])
{
Node n1=new Node();
Node n2=new Node();
Node n3=new Node();
Node n4=new Node();
Node n5=new Node();
Node.head = new Node();
Node.tail = new Node();
n1.setElement(5);
n1.setNext(n2);
n2.setElement(10);
n2.setNext(n3);
n3.setElement(20);
n3.setNext(n4);
n4.setElement(5);
n4.setNext(n5);
n5.setElement(17);
Node.head.setNext(n1);
Node.tail.setNext(n5);
n1.display();
System.out.println();
n1.insert(76);
n1.display();
System.out.println();
n1.delete(10);
n1.display();
}
}
----------------------------------Output------------------------------
----------------------------------------------------------------------
5
10
20
5
17
5
76
10
20
5
17
5
76
20
5
17
You Might Also Like :