Professional Documents
Culture Documents
import java.util.Scanner;
class node
{
int info;
node link;
temp.info=data;
temp.link=null;
if(this==null)
start=temp;
else
{
q=this;
while(q.link!=null) q=q.link;
q.link=temp;
}
}
void addatbeg(int data)
{
node start=this.link;
node tmp;
tmp=new node();
tmp.info=data;
tmp.link=start;
this.link=tmp;
}
void addafter(int data,int pos)
{
node start=this;
node tmp,q;
int i;
q=start;
for(i=0;i<pos;i++)
{
q=q.link;
if(q==null)
{
System.out.println("There are less than "+pos+" elements");
return;
}
}
tmp=new node();
tmp.link=q.link;
tmp.info=data;
q.link=tmp;
}
public void del(int data)
{
node start=this;
node tmp,q;
if(start.info==data)
{
tmp=start;
start=start.link; /*first element deleted*/
//delete(tmp);
return;
}
q=start;
while(q.link.link!=null)
{
if(q.link.info==data) /*element deleted in between*/
{
tmp=q.link;
q.link=tmp.link;
//free(tmp);
return;
}
q=q.link;
}
if(q.link.info==data) /*last element deleted*/
{
tmp=q.link;
q.link=null;
return;
}
System.out.println("Element "+data+" not found");
}
if(start==null)
{
System.out.println("List is empty");
return;
}
q=start;
System.out.println("List is:");
while(q!=null)
{
System.out.println(q.info+" ");
q=q.link;
}
System.out.println();
}
void count()
{
node q=this.link;
int cnt=0;
while(q!=null)
{
q=q.link;
cnt++;
}
System.out.println("Number of elements are "+cnt);
}
public void rev()
{
node start=this.link;
node p1,p2,p3;
if(start.link==null) return; /*only one element*/
p1=start;
p2=p1.link;
p3=p2.link;
p1.link=null;
p2.link=p1;
while(p3!=null)
{
p1=p2;
p2=p3;
p3=p3.link;
p2.link=p1;
}
this.link=p2;
}
System.out.println("Enter ur choice");
choice=cin.nextInt();
switch(choice)
{
case 1:
System.out.println("How many nodes u want:");
n=cin.nextInt();
for(i=0;i<n;i++)
{
System.out.println("Enter the element");
m=cin.nextInt();
start.create_list(m);
}
break;
case 2:
System.out.println("Enter the element");
m=cin.nextInt();
start.addatbeg(m);
break;
case 3:
System.out.println("Enter the element");
m=cin.nextInt();
System.out.println("Enter the position after which this
element is inserted");
position=cin.nextInt();
start.addafter(m,position);
break;
case 4:
if(start==null)
{
System.out.println("List is empty");
continue;
}
System.out.println("Enter the element for deletion");
m=cin.nextInt();
start.del(m);
break;
case 5:
start.display();
break;
case 6:
start.count();
break;
case 7:
start.rev();
break;
case 8:
System.out.println("Enter the element to be searched");
m=cin.nextInt();
start.search(m);
break;
case 9:
break;
default:
System.out.println("Wrong choice");
}
}