import java.io.*;
class node
{
public int x;
public node next;
}
class LinkedList
{
public node first;
LinkedList()
{
first=new node();
first.next=null;
}
void add (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
node ptr=first;
while(ptr.next!=null)
ptr=ptr.next;
ptr.next=temp;
}
void insert(int p,int v)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next=temp;
}
void del(int p)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
temp=ptr.next;
ptr.next=ptr.next.next;
temp=null;
}
void show()
{
System.out.println("\nList Elements:");
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
}
}
class SListTest
{
public static void main(String as[]) throws Exception
{
String con="";
int x,op,p,v;
LinkedList l1=new LinkedList();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add more?(y,n):");
con=br.readLine();
}while(con.equals("y"));
l1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(br.readLine());
System.out.println("Enter Value to insert:");
v= Integer.parseInt(br.readLine());
l1.insert(p,v);
}
if(op==2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(br.readLine());
l1.del(p);
}
l1.show();
}while(op<4);
}
}
/* Output: */
Enter elements to create
30
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:
30 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option:1
Enter Position to insert:2
Enter Value to insert:99
List Elements:
30 99 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4
1 comments:
Thanks to this!
Post a Comment