Saturday, 9 July 2011

Singly linked List

import java.util.*;
class Elem
{
public Elem next;
public Object data;
};
class Link
{
static Elem front=null;
static Elem back=null;
public static void main(String[] args)
{
Link l= new Link();
Scanner sc=new Scanner(System.in);
int a;
while(true)
{

System.out.println("enter your choice\n 1 for insert\n 2 for display\n 3 for exit");
a=sc.nextInt();
switch (a)
{

case 1:
System.out.println("enter a number");
String b=sc.next();
l.insert(b);
break;
case 2:
l.display();
break;
case 3:
exit();
break;
default:
System.out.println("Please enter correct choice");


}
}
}
public static void insert(Object a)
{
Elem e=new Elem(); // Create a new list element.
e.data=a; // Set the data field.
if (front==null)
{
front=e; // Back element will be set below.

}
else
{
back.next=e; // Link last elem to new element.
}
back=e; // Update back to link to new element.
}

public static void display()
{
Elem curr=front;
while (curr!=null)
{
System.out.println(curr.data);
curr=curr.next;
}

}

public static void exit()
{
System.exit(0);
}
}

No comments:

Post a Comment