0% found this document useful (0 votes)
119 views9 pages

Stack:: Data Structures Data Structures

The document discusses stacks and queues. It defines a stack as a last-in, first-out data structure where elements can only be added or removed from one end, called pushing and popping. It also discusses queue as a first-in, first-out data structure. The document provides implementations of stacks using arrays and linked lists. It also provides algorithms for conversions between infix and postfix notations using a stack.

Uploaded by

Hemanth Goli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views9 pages

Stack:: Data Structures Data Structures

The document discusses stacks and queues. It defines a stack as a last-in, first-out data structure where elements can only be added or removed from one end, called pushing and popping. It also discusses queue as a first-in, first-out data structure. The document provides implementations of stacks using arrays and linked lists. It also provides algorithms for conversions between infix and postfix notations using a stack.

Uploaded by

Hemanth Goli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

II B.Tech IT sem-1 II B.

Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES

UNIT-2: Stack & Queue int max;


Stacks: Introduction, Operations, implementation, Applications. StackN()
Queues: Introduction,Operations, implementation, Applications, Circular Queue {
System.out.println("enter max");
max=s.nextInt();
Stack: stk=new int[max];
The stack is a data structure that is very frequently used in computing as a kind of temporary }
storage. It is a list of elements to which additions and deletions can only be made at one end- void push(int e)
the top. Consequently, the stack becomes a last-in-first-out (LIFO) data structure; the last {
element added is the first to be removed. When we add an item to the top of the stack, it is if(!isFull())
called a PUSH operation and when we remove an item from the top, it is called a POP stk[++top]=e;
operation. The stack data structure maintains a stack pointer always pointing to its top. else
After pushing an item, the stack pointer moves up to point always to the last item added. System.out.println("stackoverflow");
Similarly, after popping an item, the stack pointer moves down to the next last item in the }
stack. void pop()
Stack Model {
if(!isEmpty())
POP (S) PUSH (R, S)
Stack s System.out.println("the element which is deleted from
TOP (S) Stack S the stack is "+stk[top--]);
Stack can be implemented in either Fixed size stack or Dynamic size stack. else
In fixed size stack we are using arrays. System.out.println("stackunderflow");
Ex: }
Shows a sample Stack int peek()
{
if(!isEmpty())
3 return stk[top];
2 else
1 return -1;
}
After you Push 4 the Stack would be boolean isEmpty()
{
if(top==-1)
4 return true;
else
3
return false;
2
}
1
boolean isFull()
When you Pop the Stack would be
{
if(top==max-1)
return true;
3 else
2 return false;
1 }
Stack Implementation: void display()
import java.util.*; {
class StackN for(int i=top;i>=0;i--)
{ System.out.println(stk[i]);
int top=-1; }
Scanner s= new Scanner(System.in); }
int stk[]; class StackDemo

1 VVIT, NAMBUR 2 VVIT, NAMBUR


II B.Tech IT sem-1 II B.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 :

The Postfix(Postorder) form of the above expression is "23*45/-". Postfix String

Conversion : Stack

3 VVIT, NAMBUR 4 VVIT, NAMBUR


II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES

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() }
{ }

5 VVIT, NAMBUR 6 VVIT, NAMBUR


II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES

while(!x.isEmpty()) Postfix String : 123*+4-


{
pfx=pfx+x.pop(); Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are
} operands. Thus they will be pushed into the stack in that order.
System.out.println(pfx);
}
static int precedence(char ch)
{ Expression
switch(ch)
{ Stack
case '(': return 1;
case '+': Next character scanned is "*", which is an operator. Thus, we pop the top two elements from
case '-': return 2; the stack and perform the "*" operation with the two operands. The second operand will be
case '*': the first element that is popped.
case '/':
case '%': return 3;
case '^': return 4;
}
return -1; Expression
}
} Stack

Postfix Evaluation: The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.
Infix Expression :

Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.

Postfix Expression : Expression

The Postfix(Postorder) form of the above expression is "23*45/-". Stack

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 :

Scan the Postfix string from left to right.


Initialise an empty stack.
If the scannned character is an operand, add it to the stack Expression
If the scanned character is an Operator, then pop two elements from stack. Store them
to x and y. Now evaluate x operator y. Let the result of this operation be retVal. Push Stack
retVal into the stack.
Repeat the step till all the characters are scanned. The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.
After all characters are scanned, we will have only one element in the stack. Return
that element.

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

x.push(infx.charAt(i)); Front Rear


} After an Dequeue operation
}
} 7 9
while(!x.isEmpty()) 0 1 2 3 4
{
pfx=pfx+x.pop(); Front Rear
}
System.out.println(pfx); But there is one potential problem with the above implementation after some Enqueue
} operation the Queue appears to be full. (Suppose rear = 4 and front = 2 for 5 cell queue the
static int precedence(char ch) queue appears to be full but not). Then you cannot insert further till the queue is empty.
{ The Simple solution is that whenever front and rear gets to the end of the array, it is wrapped
switch(ch) around to the beginning. This is known as circular Queue.
{
case '(': return 1; Applications of queues:
case '+':
case '-': return 2; 1. Uses of Queues in operating systems: Operating system maintains several queues like
case '*': ready queue, device queue etc. for handling multiple processes.
case '/':
case '%': return 3; 2. Use of Queue in Network Ex: for Queuing jobs in file Server.
case '^': return 4;
} 3. A Whole branch of mathematics, known as queuing theory, deals with computing,
return -1; probabilistically, how long users expect to wait on a line, how long the line gets, and other
} such questions.
}
Implementation of Queue:
Queue import java.util.Scanner;
class Queue1
Like Stacks, Queues are lists. With a queue, however, insertion is done at one end called rear {
end, where as deletion is performed at the other end called front end. Some times it is called int max,f,r;
FIFO (First in First out) List. int q[];
The basic operations on a queue are Enqueue, which inserts an element at the end of Queue1()
the list (called the rear), and Dequeue, which deletes the elements at the start of the list. {
Model of a Queue is f=r=-1;
max=5;
q=new int[max];
Dequeue(Q) Queue Q Enqueue(Q) }
Queue Q void enQueue(int e)
Array Implementation of Queue {
Consider a queue, which can add a maximum of five elements if(!isFull())
After Create {
q[++r]=e;
if(f==-1)
0 1 2 3 4 f++;
Front = 0, Rear=0 }
After adding 5, 7, and 9 in same sequence the queue will be else
{
5 7 9 System.out.println("queue is full");
}
0 1 2 3 4
}
11 VVIT, NAMBUR 12 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) {

13 VVIT, NAMBUR 14 VVIT, NAMBUR


II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES

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.*;

15 VVIT, NAMBUR 16 VVIT, NAMBUR


II B.Tech IT sem-1 II B.Tech IT sem-1
DATA STRUCTURES DATA STRUCTURES

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()

17 VVIT, NAMBUR 18 VVIT, NAMBUR

You might also like