¨ Stack in simple terms can be explained as a heap of objects placed one over the other.
¨ The last placed object can be accessed first, and it is said to be “Last-in-First- out” (LIFO) method.
¨ In a stack, the elements are added at the top and removed from the top.
Stack can be implemented mainly in two ways
1. Using arrays
2. Using Linked lists.
In both the ways, we need to write the “push()” and “pop()” functions.
1. Program to implement PUSH and POP operations on Stack using array method.
class Stack
{
private static int MAX=10;
private int a[]=new int[MAX];
int top;
Stack()
{
top=0;
}
public void push(int v)
{
if(top
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop()
{
if(top>0)
return a[--top];
else
{
System.out.println("Underflow");
return -1;
}
}
}
class StackArray
{
public static void main(String as[])
{
Stack s1=new Stack();
s1.push(30);
s1.push(40);
s1.push(50);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}
/* Output */
50
40
30
2. Program to implement PUSH and POP operations on Stack using Linked list method.
class node
{
public int x;
public node next;
}
class Stack
{
public node top;
Stack()
{
top=null;
}
void push (int v)
{
node temp=new node();
temp.x=v;
temp.next=top;
top=temp;
}
int pop()
{
int v=top.x;
node temp=top;
top=top.next;
temp=null;
return v;
}
}
class StackList
{
public static void main(String as[])
{
Stack s1=new Stack();
s1.push(30);
s1.push(40);
s1.push(50);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}
/* Output */
50
40
30
0 comments:
Post a Comment