// Stack implementation using linked list
import java.util.*;
class stlink
{
int info;
stlink next;
}
class rklinkstack
{
public static void main(String []args)
{
stack sl=new stack();
int ch,x;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.printf("\n ***MENU***\n");
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.DISPLAY");
System.out.println("4.EXIT");
System.out.println("Enter Ur Choice:");
ch=sc.nextInt();
switch(ch)
{
case 1: System.out.println("Enter any Number into stack :");
x=sc.nextInt();
sl.push(x);
break;
case 2: sl.pop();
break;
case 3: sl.display();
break;
case 4: System.exit(0);
default: System.out.println("Wrong choice");
}
}
}
}
class stack
{
stlink start,top,tmp;
void push(int x)
{
tmp=new stlink();
tmp.info=x;
tmp.next=top;
top=tmp;
}
void pop()
{
if(top==null)
System.out.println("Stack underflow");
else
{
tmp=top;
System.out.println("Deleted Element is:"+tmp.info);
top=top.next;
}
}
void display()
{
if(top==null)
System.out.println("Stack is empty");
else
{
start=top;
System.out.printf("Stack linked list is : %h --> %d ",start,start.info);
while(start.next!=null)
{
start=start.next;
System.out.printf(" || %h -->%d ",start,start.info);
}
System.out.printf("||%h",start.next);
}
}
}
output:
import java.util.*;
class stlink
{
int info;
stlink next;
}
class rklinkstack
{
public static void main(String []args)
{
stack sl=new stack();
int ch,x;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.printf("\n ***MENU***\n");
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.DISPLAY");
System.out.println("4.EXIT");
System.out.println("Enter Ur Choice:");
ch=sc.nextInt();
switch(ch)
{
case 1: System.out.println("Enter any Number into stack :");
x=sc.nextInt();
sl.push(x);
break;
case 2: sl.pop();
break;
case 3: sl.display();
break;
case 4: System.exit(0);
default: System.out.println("Wrong choice");
}
}
}
}
class stack
{
stlink start,top,tmp;
void push(int x)
{
tmp=new stlink();
tmp.info=x;
tmp.next=top;
top=tmp;
}
void pop()
{
if(top==null)
System.out.println("Stack underflow");
else
{
tmp=top;
System.out.println("Deleted Element is:"+tmp.info);
top=top.next;
}
}
void display()
{
if(top==null)
System.out.println("Stack is empty");
else
{
start=top;
System.out.printf("Stack linked list is : %h --> %d ",start,start.info);
while(start.next!=null)
{
start=start.next;
System.out.printf(" || %h -->%d ",start,start.info);
}
System.out.printf("||%h",start.next);
}
}
}
output:
No comments:
Post a Comment