Stack:: Data Structures Data Structures
Stack:: Data Structures Data Structures
Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES
{ In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is
public static void main(String[] args) abc*+. The algorithm for the conversion is as follows :
{ Scan the Infix string from left to right.
StackN x=new StackN(); Initialize an empty stack.
Scanner s= new Scanner(System.in); If the scanned character is an operand, add it to the Postfix string.
int ch; If the scanned character is an operator and if the stack is empty Push the character to
while(true) stack.
{ If the scanned character is an Operator and the stack is not empty, compare the
System.out.println("enter your choice"); precedence of the character with the element on top of the stack (topStack).
ch=s.nextInt(); If topStack has lower precedence over the scanned character Push the scanned
switch(ch) character to stack.
{ Else(higher or equal precedence) Pop the stack and add it to the postix string.
case 1:x.push(s.nextInt()); Repeat this step as long as stack is not empty and topStack has less precedence
break; over the character.
case 2:x.pop(); If a left parenthesis is encountered, push it onto Stack.
break; If a right parenthesis is encountered ,then:
case 3:System.out.println(x.peek()); Repeatedly pop from Stack and add to postfix string until left
break; parenthesis is encountered.
case 4:x.display(); Remove the left Parenthesis.
break; Repeat this step till all the characters are scanned.
default:return; If stack is not empty Pop the stack and add it to postfix string
} Repeat this step as long as stack is not empty.
} Return the Postfix string.
} Example :
}
Applications of Stacks: Let us see how the above algorithm will be imlemented using an example.
1. Compilers will take the help of stack for checking syntax errors (Symbol Balancing) Infix String : a+b*c-d
2. Stacks were used in evaluating postfix expressions (Reverse polish notation).
3. Stacks are used in conversion of infix expressions to postfix expressions. Initially the Stack is empty and our Postfix string has no characters. Now, the first character
4. Stack for matching brackets in an expression. scanned is 'a'. 'a' is added to the Postfix string. The next character scanned is '+'. It being an
5. Stacks were used in function call. operator, it is pushed to the stack.
i.e. When there is a function call, all the important information that needs to be saved,
such as register values and the return addresses are saved onto the stack. The information
saved is called either an activation record or stack frame. Postfix String
Applications :
Reversing a list: Stack
Factorial calculation:
Infix to Postfix Conversion: Next character scanned is 'b' which will be placed in the Postfix string. Next character is '*'
Infix Expression : which is an operator. Now, the top element of the stack is '+' which has lower precedence
than '*', so '*' will be pushed to the stack.
Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.
Postfix Expression :
Conversion : Stack
return stk[top];
The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. }
The topmost character in the stack is '*' which has a higher precedence than '-'. Thus '*' will boolean isEmpty()
be popped out from the stack and added to the Postfix string. Even now the stack is not {
empty. Now the topmost element of the stack is '+' which has equal priority to '-'. So pop the if(top==-1)
'+' from the stack and add it to the Postfix string. The '-' will be pushed to the stack. return true;
else
return false;
}
}
Postfix String class InfxToPfx
{
Stack public static void main(String[] args)
{
Next character is 'd' which is added to Postfix string. Now all characters have been scanned Stack1 x=new Stack1();
so we must pop the remaining elements from the stack and add it to the Postfix string. At this Scanner s=new Scanner(System.in);
stage we have only a '-' in the stack. It is popped out and added to the Postfix string. So, after String infx;
all characters are scanned, this is how the stack and Postfix string will be : String pfx="";
System.out.println("enter the infix string!");
infx=s.nextLine();
for(int i=0;i<infx.length();i++)
{
Postfix String if (Character.isLetter(infx.charAt(i)))
{
Stack pfx=pfx+infx.charAt(i);
}
End result : else if (infx.charAt(i)=='(')
{
Infix String : a+b*c-d
x.push('(');
Postfix String : abc*+d- }
else if(infx.charAt(i)==')')
Follow the procedure in which is in your note book {
char y;
Program for converting infix to postfix: while((y=x.pop())!='(')
pfx=pfx+y;
import java.util.*; }
class Stack1 else
{ {
char stk[]=new char[20]; if(x.isEmpty() ||
int top=-1; precedence(x.peek())<precedence(infx.charAt(i)))
void push(char c) x.push(infx.charAt(i));
{ else
stk[++top]=c; {
} while(
char pop() !x.isEmpty()&&precedence(x.peek())>=precedence(infx.charAt(i)))
{ pfx=pfx+x.pop();
return stk[top--]; x.push(infx.charAt(i));
} }
char peek() }
{ }
Postfix Evaluation: The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.
Infix Expression :
Evaluation : Next character scanned is "+", which is an operator. Thus, we pop the top two elements from
the stack and perform the "+" operation with the two operands. The second operand will be
In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is the first element that is popped.
abc*+. The algorithm for the conversion is as follows :
Example :
Expression
Let us see how the above algorithm will be imlemented using an example.
Stack
7 VVIT, NAMBUR 8 VVIT, NAMBUR
II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES
return stk[top--];
Next character scanned is "4", which is added to the stack. }
char peek()
{
return stk[top];
}
Expression boolean isEmpty()
{
Stack if(top==-1)
return true;
Next character scanned is "-", which is an operator. Thus, we pop the top two elements from else
the stack and perform the "-" operation with the two operands. The second operand will be return false;
the first element that is popped. }
}
class InfxToPfx
{
public static void main(String[] args)
Expression {
Stack1 x=new Stack1();
Stack Scanner s=new Scanner(System.in);
String infx;
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. String pfx="";
System.out.println("enter the infix string!");
infx=s.nextLine();
for(int i=0;i<infx.length();i++)
{
Expression if (Character.isLetter(infx.charAt(i)))
{
Stack pfx=pfx+infx.charAt(i);
}
Now, since all the characters are scanned, the remaining element in the stack (there will be else if (infx.charAt(i)=='(')
only one element in the stack) will be returned. {
x.push('(');
End result : }
else if(infx.charAt(i)==')')
Postfix String : 123*+4- {
Result : 3 char y;
while((y=x.pop())!='(')
Program for postfix expression evaluation:
pfx=pfx+y;
}
import java.util.*;
else
class Stack1
{
{
if(x.isEmpty() ||
char stk[]=new char[20];
precedence(x.peek())<precedence(infx.charAt(i)))
int top=-1;
x.push(infx.charAt(i));
void push(char c)
else
{
{
stk[++top]=c;
while(
}
!x.isEmpty()&&precedence(x.peek())>=precedence(infx.charAt(i)))
char pop()
pfx=pfx+x.pop();
{
9 VVIT, NAMBUR 10 VVIT, NAMBUR
II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES
void deQueue() {
{ System.out.println("enter your choice ");
if(!isEmpty()) ch=s.nextInt();
{ switch(ch)
System.out.println("the element which is going to deleted is "+q[f]); {
if(f==r) case 1:x.enQueue(s.nextInt());
f=r=-1; break;
else case 2:x.deQueue();
f++; break;
} case 3:x.display();
else break;
{ default:return;
System.out.println("queue is empty"); }
} }
} }
boolean isEmpty() }
{ Implement Queue using Stacks
if(f==-1)
A queue can be implemented using two stacks. Let queue to be implemented be q and stacks
return true;
else used to implement q be stack1 and stack2. q can be implemented in two ways:
return false;
} Method (By making deQueue operation costly)
boolean isFull() In this method, in en-queue operation, the new element is entered at the top of stack1. In de-
{
if(r==max-1) queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top
return true; of stack2 is returned.
else
return false; enQueue(q, x)
}
void display() 1) Push x to stack1 (assuming size of stacks is unlimited).
{
if(!isEmpty())
{ deQueue(q)
for (int i=f;i<=r;i++) 1) If both stacks are empty then error.
{
System.out.println(q[i]); 2) If stack2 is empty
} While stack1 is not empty, push everything from satck1 to stack2.
}
else 3) Pop the element from stack2 and return it.
System.out.println("Queue is empty");
}
} Program for Queue using two stacks
class QueueDemo
{ import java.util.Scanner;
public static void main(String[] args) class TwoStk
{ {
Queue1 x=new Queue1(); int top1,top2;
Scanner s=new Scanner(System.in); int s1[],s2[];
int ch; TwoStk()
while(true) {
top1=top2=-1; {
s1=new int[20]; case 1:x.enQueue(s.nextInt());
s2=new int[20]; break;
} case 2:x.deQueue();
void push1(int e) break;
{ default:return;
s1[++top1]=e; }
} }
int pop1() }
{ }
return s1[top1--]; What is Round-Robin Scheduling?
}
It is one of the oldest, simplest, fairest and most widely used scheduling algorithms, designed
void push2(int e)
especially for time-sharing systems. A small unit of time, called timeslice or quantum, is
{
defined. All runnable processes are kept in a circular queue. The CPU scheduler goes around
s2[++top2]=e;
this queue, allocating the CPU to each process for a time interval of one quantum. New
}
processes are added to the tail of the queue.
int pop2()
{ The CPU scheduler picks the first process from the queue, sets a timer to interrupt after one
return s2[top2--]; quantum, and dispatches the process.
} If the process is still running at the end of the quantum, the CPU is preempted and the process
void enQueue(int e) is added to the tail of the queue. If the process finishes before the end of the quantum, the
{ process itself releases the CPU voluntarily. In either case, the CPU scheduler assigns the CPU
push1(e); to the next process in the ready queue. Every time a process is granted the CPU.
}
void deQueue() Circular queue :
{ One limitation of ordinary queue is, we can insert a new element into queue if rear<max .
if (top1==-1 && top2==-1)
System.out.println("Queue underflow"); locations
else if(top2==-1)
Front Rear
{
while(top1!=-1) 4 5 6 7 8 9
push2(pop1());
System.out.println("the element to be deleted is "+pop2()); Circular queue eliminate the problem linear queue.
} Circular queue is a queue but it is not linear in structure insted it is circular . In other words
else ,the FRONT and REAR variables which display a linear movements(left to right) over a
System.out.println("the element to be deleted is "+pop2()); queue, in circular queue they display a circular movements(clock wise)
}
} Now we can place the next element in the first position in the above example using
class QueueStack circular queue. For the circular movements FRONT and REAR can be increment like
{ Rear Front
public static void main(String[] args)
{ 10 4 5 6 7 8 9
TwoStk x=new TwoStk();
Scanner s=new Scanner(System.in);
int ch; For the circular movements FRONT and REAR can be increment like
while(true) Rear=(Rear%max)+1;
{
System.out.println("enter your choice "); Fonrt=(Front%max)+1;
ch=s.nextInt(); Implementation of circular queue:
switch(ch) import java.util.*;
class CQueue {
{ if (!isEmpty())
int q[]; {
int f,r,size; if(f<=r)
CQueue() {
{ for (int i=f;i<=r;i++)
f=r=-1; System.out.println(q[i]);
size=5; }
q=new int[size]; else
} {
void enQueue(int e) for(int i=f; i!=r;i=(i+1)%size)
{ System.out.println(q[i]);
if(!isFull()) System.out.println(q[r]);
{ }
r=(r+1)%size; }
q[r]=e; else
if(f==-1) System.out.println("queue is empty");
f=0; }
} }
else class CQueueDemo
System.out.println("Queue is full"); {
} public static void main(String[] args)
void deQueue() {
{ CQueue x=new CQueue();
if(!isEmpty()) Scanner s=new Scanner(System.in);
{ int ch;
System.out.println("the element that is to be deleted is "+q[f]); while(true)
if(f==r) {
f=r=-1; System.out.println("enter your choice ");
else ch=s.nextInt();
f=(f+1)%size; switch(ch)
} {
else case 1:x.enQueue(s.nextInt());
System.out.println("Queue is empty"); break;
} case 2:x.deQueue();
boolean isEmpty() break;
{ case 3:x.display();
if(f==-1) break;
return true; default:return;
else }
return false; }
} }
boolean isFull() }
{
if((r+1)%size==f)
return true;
else
return false;
}
void display()