import javax.swing.*;
class Node
{
int data; // this can be replaced by the data component of the node later on. e.g. video Video;
Node next;
}
public class LinkedListDemo
{
private Node head = null;
private Node tail = null;
public static void main (String args[])
{
new LinkedListDemo();
}
public LinkedListDemo()
{
int n = 0;
head = null;
tail = null;
while (n != -999)
{
n = Integer.parseInt(JOptionPane.showInputDialog("Enter a number of integer value: "));
if (n == 0)
{
System.exit(0);
}
add(n);
display();
}
int item = Integer.parseInt(JOptionPane.showInputDialog("Input data to delete: "));
delete(item);
display();
}
public void add(int d)
{
Node newNode = new Node();
Node current = new Node();
current = head;
if (head == null)
{
head = newNode;
tail = newNode;
newNode.data = d;
newNode.next = null;
}
else if (d < head.data)
{
newNode.data = d;
newNode.next = head;
head = newNode;
}
else if (d > tail.data)
{
newNode.data = d;
newNode.next = null;
tail.next = newNode;
tail = newNode;
}
else
{
while (current != tail)
{
if (d >= current.data && d <= current.next.data)
{
newNode.data = d;
newNode.next = current.next;
current.next = newNode;
current = tail;
}
else
{
current = current.next;
}
}
}
}
public void delete (int d)
{
boolean found = false;
Node current = new Node();
Node tempNode = new Node();
tempNode = null;
current = head;
while (!found && current.next != null)
{
if (current.data == d)
{
found = true;
}
else
{
tempNode = current;
current = current.next;
}
}
if (found && head == tail)
{
head = null;
tail = null;
}
else if (found && current == tail)
{
tail = tempNode;
tempNode.next = null;
}
else if (found && current == head)
{
head = current.next;
}
else if (found)
{
tempNode.next = current.next;
}
if (!found)
{
System.out.println("Data in list");
}
}
public void display()
{
Node current = new Node();
current = head;
while (current != null)
{
System.out.println(current.data + "..");
current = current.next;
}
System.out.println("End of list \n");
}
}