UNIT - 2 : STACK & QUEUE
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and
Linked Implementation of Stack in C, Application of stack: Prefix and Postfix
Expressions, Evaluation of postfix expression, Iteration and Recursion- Principles of
recursion, Tail recursion, Removal of recursion Problem solving using iteration and
recursion with examples such as binary search, Fibonacci numbers, and Hanoi
towers. Tradeoffs between iteration and recursion.
Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues,
Array and linked implementation of queues in C, Dequeue and Priority Queue
STACK
• Stack is a linear data structure which follows a particular order in which the
operations are performed.
• Insertion of element into stack is called PUSH and deletion of element from stack is
called POP.
• The order may be LIFO(Last In First Out) or FILO(First In Last Out).
STACK
OPERATIONS ON STACK
• NewStack( ): It creates a new stack that is empty. It needs no parameter and returns
an empty stack.
• PUSH(Item): It adds a new item to the top of the stack.
• POP( ): It removes the top item from the stack.
• PEEK( ): It returns the top item from the stack but does not remove it.
• IsEmpty( ): It tests whether the stack is empty.
• IsFull( ): It tests whether the stack is full.
• Size( ): It returns the number of items on the stack.
STACK CONDITIONS
STACK : PUSH
• The process of adding one element or item to the stack is represented by an operation called
as the PUSH operation.
• The new element is added at the topmost position of the stack.
STACK : PUSH
ALGORITHM: STACK is the array with N elements. TOP is the pointer to the top
of the element of the array. ITEM to be inserted.
PUSH (STACK, TOP, SIZE, ITEM)
Step 1: if TOP = N-1 then [Check Overflow]
PRINT “ STACK is Full or Overflow”
Exit [End if]
Step 2: TOP = TOP + 1 [Increment the TOP]
Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
STACK : POP
• The process of deleting one
element or item from the stack is
represented by an operation
called as the POP operation.
• When elements are removed
continuously from a stack, it
shrinks at same end i.e. top
STACK : POP
STACK is the array with N elements. TOP is the pointer to the top of the element
of the array. ITEM to be inserted.
ALGORITHM: POP (STACK, TOP, ITEM)
Step 1: if TOP = -1 then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit [End if]
Step 2: ITEM = STACK[TOP] [copy the TOP Element]
Step 3: TOP = TOP -1 [Decrement the TOP]
Step 4: Return
STACK : PEEK OR TOP
• The process of returning the top item from the stack but does not remove it
called as the POP operation.
STACK is the array with N elements. TOP is the pointer to the top of the element
of the array.
ALGORITHM: PEEK (STACK, TOP)
Step 1: if TOP = NULL then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit [End if]
Step 2: Return STACK[TOP] [Return the top element of the stack]
Step 3:Exit
STACK : PEEK OR TOP
• The process of returning the top item from the stack but does not remove it
called as the POP operation.
STACK is the array with N elements. TOP is the pointer to the top of the element
of the array.
ALGORITHM: PEEK (STACK, TOP)
Step 1: if TOP = NULL then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit [End if]
Step 2: Return (STACK[TOP] ) [Return the top element of the stack]
Step 3:Exit
FUNCTION IN C FOR PUSH
1. function name. 2. value to be inserted 3. top 4. name of array = stack[4]; 5. loop =
void push(int value)
{
if(top==n-1)
printf(“stack is full . overflow”);
else
top=top+1;
stack[top]=value;
}
index stack
3 40
2 30
1 20
0 10
FUNCTION IN C FOR POP
1. function name. 2. top 3. name of array = stack[4]; 4. loop =
void POP()
{
if(top==-1)
printf(“stack is empty so underflow condition”);
else
top=top-1;
}
index stack
3 40
2 30
1 20
0 10
FUNCTION FOR TOP
1. function name. 2. top 3. name of array = stack[4]; 4. loop =
TOP()
{
if(top==-1)
printf(“stack is empty.”);
else
printf(“top = %d , value at top = %d”,top, stack[top]);
}
top=3, value at top= 12
index stack
3- TOP 12
2 5
1 6
0 88
FUNCTION FOR display
1. function name. 3. top 4. name of array = stack[4]; loop =
display()
{
if(top == -1)
printf(“stack is empty.”);
else
for(i = 0 ; i<= top ; i++)
printf(“%d”, stack[i]);
}
index stack
2 = top 3
1 5
0 8
#include<stdio.h>
int stack[10],choice,n,top,x,i;
void push( );
void pop( );
void display();
int main( )
{
top = -1; // Initially there is no
element in stack
printf("n Enter the size of STACK :
");
scanf("%d",&n);
do {
printf(" 1.PUSH 2.POP 3.DISPLAY
4.EXIT");
printf("nEnter the choice : ");
scanf("%d",&choice);
printf("STACK
OVERFLOW");
}
else
{
printf("Enter a value
to be pushed : ");
scanf("%d",&x);
top++; // TOP is
incremented after an
element is pushed
stack[top] = x; // The
pushed element is made
as TOP
}}
void pop( )
{
if(top == -1)
{
printf("STACK
UNDERFLOW");
else
{
printf("nThe popped
element is
%d",stack[top]);
top--; // Decrement
TOP after a pop
}}
void display( )
{
if(top >= 0)
{
// Print the stack
printf("nELEMENTS IN
THE STACKnn");
for(i = top ; i >= 0 ; i--)
printf("%dt",stack[i]);
}
else
{
printf("nEMPTY
STACKn");
}
return 0;
}
switch(choice)
{
case 1: { push( ); break; }
case 2: { pop( ); break; }
case 3: { display( ); break;
}
case 4:
{
break;
}
default:
{
printf ("nInvalid Choicen");
}}}
while(choice!=4);
return 0;
}
void push( )
{
if(top == n - 1)
{
APPLICATION OF STACK
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Saving local variables when one function calls another, and this one calls
another
• It is used to reverse a word. You push a given word to stack –letter by letter
and then pop letter from the stack.
• “Undo” mechanism in text editor.
• Backtracking: This is a process when you need to access the most recent data
element in a series of elements. Once you reach a dead end, you must
backtrack.
• Language Processing: Compiler’s syntax check for matching braces in
implemented by using stack.
• Conversion of decimal number to binary.
• To solve tower of Hanoi.
• Conversion of infix expression into prefix and postfix.
• Quick sort
• Runtime memory management.
• Implementation of DFS in Trees & Graphs
QUEUE
• A queue is an ordered collection of items where an item is inserted at one end
called the “rear” and an existing item is removed at the other end, called the “front”.
• Queue is also called as FIFO list i.e. First-In First-Out.
• In the queue only two operations are allowed enqueue and dequeue.
• Enqueue means to insert an item into back of the queue.
• Dequeue means removing the front item.The people standing in a railway
reservation row are an example of queue.
QUEUE
The queue can be implemented into two ways:
1. Using arrays (Static implementation) 2.Using pointer (Dynamic implementation)
TYPES OF QUEUE
• LINEAR OR SIMPLE QUEUE
• CIRCULAR QUEUE
• DEQUEUE (DOUBLY ENDED QUEUE)
• PRIORITY QUEUE
SIMPLE OR LINEAR QUEUE
• In Linear Queue, an insertion takes place from one end while the deletion occurs from
another end. The end at which the insertion takes place is known as the rear end, and
the end at which the deletion takes place is known as front end. It strictly follows the
FIFO rule.
• The major drawback of using a linear Queue is that insertion is done only from the
rear end. If the first three elements are deleted from the Queue, we cannot insert more
elements even though the space is available in a Linear Queue. In this case, the linear
Queue shows the overflow condition as the rear is pointing to the last element of the
Queue.
(Simple or Linear) QUEUE : INSERTION & DELETION
Step-1: [Check for overflow]
if( ==size-1)
Print("Queue is Overflow”);
return;
Step-2: [Insert Element]
else if (front = = -1 || rear == -1)
front=rear=0;
q[rear]=Value;
[Set rear and front pointer]
else
q[++rear]=value;
Step-3: return
Step-1 [ Check for front pointer]
if (front==-1)
print(" Queue is Underflow”);
return;
Step-2 [Perform deletion]
else
if (front==rear)
front= rear=-1;
else
Step-3 : Return
#include <stdio.h>
#define MAX 10
int QUEUE[MAX],front=-1,rear=-1;
void insert(int queue[ ],int x)
{
if(rear==-1)
{
front=rear=0;
queue[rear]=x;
}
else if(rear==MAX-1)
{
printf("nQUEUE is full.n");
return;
}
else
{
rear++;
queue[rear]=x;
}
printf("nItem inserted..");
int main()
{
int x,choice;
while(1)
{
printf("n QUEUE Elements are :");
display(QUEUE);
printf("nn Enter choice (1:Insert, 2:Display,
3:Remove, 0:Exit):");
scanf("%d",&choice);
switch(choice)
{
case 0:
exit(1);
break;
case 1:
printf("Enter an element to insert:");
scanf("%d",&x);
insert(QUEUE,x);
break;
case 2:
display(QUEUE);
break;
case 3:
delete(QUEUE);
break;
default:
printf("nInvalid choicen");
break;
}
}
return 0;
APPLICATIONS OF QUEUE
• Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrive i.e First come first served.
• Implementation of BFS in Trees & Graphs
• In networks, there are mail queues and queues in routers/switches.
• In operating systems, queues are used in Semaphores, Spooling in printers, FCFS (First
come First serve) scheduling, Buffer for devices like keyboards.
• In the case of transferring the data asynchronously (i.e. it is not necessary to receive and
send the data at the same rate) between two processes. For example, IO Buffers, pipes, file
IO, etc
• In real life scenario, Call Center phone systems uses Queues to hold people calling them in
an order, until a service representative is free.

Stack and Queue.pptx university exam preparation

  • 1.
    UNIT - 2: STACK & QUEUE Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C, Application of stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Iteration and Recursion- Principles of recursion, Tail recursion, Removal of recursion Problem solving using iteration and recursion with examples such as binary search, Fibonacci numbers, and Hanoi towers. Tradeoffs between iteration and recursion. Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of queues in C, Dequeue and Priority Queue
  • 2.
    STACK • Stack isa linear data structure which follows a particular order in which the operations are performed. • Insertion of element into stack is called PUSH and deletion of element from stack is called POP. • The order may be LIFO(Last In First Out) or FILO(First In Last Out).
  • 3.
  • 4.
    OPERATIONS ON STACK •NewStack( ): It creates a new stack that is empty. It needs no parameter and returns an empty stack. • PUSH(Item): It adds a new item to the top of the stack. • POP( ): It removes the top item from the stack. • PEEK( ): It returns the top item from the stack but does not remove it. • IsEmpty( ): It tests whether the stack is empty. • IsFull( ): It tests whether the stack is full. • Size( ): It returns the number of items on the stack.
  • 5.
  • 6.
    STACK : PUSH •The process of adding one element or item to the stack is represented by an operation called as the PUSH operation. • The new element is added at the topmost position of the stack.
  • 7.
    STACK : PUSH ALGORITHM:STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ITEM to be inserted. PUSH (STACK, TOP, SIZE, ITEM) Step 1: if TOP = N-1 then [Check Overflow] PRINT “ STACK is Full or Overflow” Exit [End if] Step 2: TOP = TOP + 1 [Increment the TOP] Step 3: STACK[TOP] = ITEM [Insert the ITEM] Step 4: Return
  • 8.
    STACK : POP •The process of deleting one element or item from the stack is represented by an operation called as the POP operation. • When elements are removed continuously from a stack, it shrinks at same end i.e. top
  • 9.
    STACK : POP STACKis the array with N elements. TOP is the pointer to the top of the element of the array. ITEM to be inserted. ALGORITHM: POP (STACK, TOP, ITEM) Step 1: if TOP = -1 then [Check Underflow] PRINT “ STACK is Empty or Underflow” Exit [End if] Step 2: ITEM = STACK[TOP] [copy the TOP Element] Step 3: TOP = TOP -1 [Decrement the TOP] Step 4: Return
  • 10.
    STACK : PEEKOR TOP • The process of returning the top item from the stack but does not remove it called as the POP operation. STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ALGORITHM: PEEK (STACK, TOP) Step 1: if TOP = NULL then [Check Underflow] PRINT “ STACK is Empty or Underflow” Exit [End if] Step 2: Return STACK[TOP] [Return the top element of the stack] Step 3:Exit
  • 11.
    STACK : PEEKOR TOP • The process of returning the top item from the stack but does not remove it called as the POP operation. STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ALGORITHM: PEEK (STACK, TOP) Step 1: if TOP = NULL then [Check Underflow] PRINT “ STACK is Empty or Underflow” Exit [End if] Step 2: Return (STACK[TOP] ) [Return the top element of the stack] Step 3:Exit
  • 12.
    FUNCTION IN CFOR PUSH 1. function name. 2. value to be inserted 3. top 4. name of array = stack[4]; 5. loop = void push(int value) { if(top==n-1) printf(“stack is full . overflow”); else top=top+1; stack[top]=value; } index stack 3 40 2 30 1 20 0 10
  • 13.
    FUNCTION IN CFOR POP 1. function name. 2. top 3. name of array = stack[4]; 4. loop = void POP() { if(top==-1) printf(“stack is empty so underflow condition”); else top=top-1; } index stack 3 40 2 30 1 20 0 10
  • 14.
    FUNCTION FOR TOP 1.function name. 2. top 3. name of array = stack[4]; 4. loop = TOP() { if(top==-1) printf(“stack is empty.”); else printf(“top = %d , value at top = %d”,top, stack[top]); } top=3, value at top= 12 index stack 3- TOP 12 2 5 1 6 0 88
  • 15.
    FUNCTION FOR display 1.function name. 3. top 4. name of array = stack[4]; loop = display() { if(top == -1) printf(“stack is empty.”); else for(i = 0 ; i<= top ; i++) printf(“%d”, stack[i]); } index stack 2 = top 3 1 5 0 8
  • 16.
    #include<stdio.h> int stack[10],choice,n,top,x,i; void push(); void pop( ); void display(); int main( ) { top = -1; // Initially there is no element in stack printf("n Enter the size of STACK : "); scanf("%d",&n); do { printf(" 1.PUSH 2.POP 3.DISPLAY 4.EXIT"); printf("nEnter the choice : "); scanf("%d",&choice); printf("STACK OVERFLOW"); } else { printf("Enter a value to be pushed : "); scanf("%d",&x); top++; // TOP is incremented after an element is pushed stack[top] = x; // The pushed element is made as TOP }} void pop( ) { if(top == -1) { printf("STACK UNDERFLOW"); else { printf("nThe popped element is %d",stack[top]); top--; // Decrement TOP after a pop }} void display( ) { if(top >= 0) { // Print the stack printf("nELEMENTS IN THE STACKnn"); for(i = top ; i >= 0 ; i--) printf("%dt",stack[i]); } else { printf("nEMPTY STACKn"); } return 0; } switch(choice) { case 1: { push( ); break; } case 2: { pop( ); break; } case 3: { display( ); break; } case 4: { break; } default: { printf ("nInvalid Choicen"); }}} while(choice!=4); return 0; } void push( ) { if(top == n - 1) {
  • 17.
    APPLICATION OF STACK •Page-visited history in a Web browser • Undo sequence in a text editor • Saving local variables when one function calls another, and this one calls another • It is used to reverse a word. You push a given word to stack –letter by letter and then pop letter from the stack. • “Undo” mechanism in text editor. • Backtracking: This is a process when you need to access the most recent data element in a series of elements. Once you reach a dead end, you must backtrack. • Language Processing: Compiler’s syntax check for matching braces in implemented by using stack. • Conversion of decimal number to binary. • To solve tower of Hanoi. • Conversion of infix expression into prefix and postfix. • Quick sort • Runtime memory management. • Implementation of DFS in Trees & Graphs
  • 18.
    QUEUE • A queueis an ordered collection of items where an item is inserted at one end called the “rear” and an existing item is removed at the other end, called the “front”. • Queue is also called as FIFO list i.e. First-In First-Out. • In the queue only two operations are allowed enqueue and dequeue. • Enqueue means to insert an item into back of the queue. • Dequeue means removing the front item.The people standing in a railway reservation row are an example of queue.
  • 19.
    QUEUE The queue canbe implemented into two ways: 1. Using arrays (Static implementation) 2.Using pointer (Dynamic implementation)
  • 20.
    TYPES OF QUEUE •LINEAR OR SIMPLE QUEUE • CIRCULAR QUEUE • DEQUEUE (DOUBLY ENDED QUEUE) • PRIORITY QUEUE
  • 21.
    SIMPLE OR LINEARQUEUE • In Linear Queue, an insertion takes place from one end while the deletion occurs from another end. The end at which the insertion takes place is known as the rear end, and the end at which the deletion takes place is known as front end. It strictly follows the FIFO rule. • The major drawback of using a linear Queue is that insertion is done only from the rear end. If the first three elements are deleted from the Queue, we cannot insert more elements even though the space is available in a Linear Queue. In this case, the linear Queue shows the overflow condition as the rear is pointing to the last element of the Queue.
  • 22.
    (Simple or Linear)QUEUE : INSERTION & DELETION Step-1: [Check for overflow] if( ==size-1) Print("Queue is Overflow”); return; Step-2: [Insert Element] else if (front = = -1 || rear == -1) front=rear=0; q[rear]=Value; [Set rear and front pointer] else q[++rear]=value; Step-3: return Step-1 [ Check for front pointer] if (front==-1) print(" Queue is Underflow”); return; Step-2 [Perform deletion] else if (front==rear) front= rear=-1; else Step-3 : Return
  • 23.
    #include <stdio.h> #define MAX10 int QUEUE[MAX],front=-1,rear=-1; void insert(int queue[ ],int x) { if(rear==-1) { front=rear=0; queue[rear]=x; } else if(rear==MAX-1) { printf("nQUEUE is full.n"); return; } else { rear++; queue[rear]=x; } printf("nItem inserted.."); int main() { int x,choice; while(1) { printf("n QUEUE Elements are :"); display(QUEUE); printf("nn Enter choice (1:Insert, 2:Display, 3:Remove, 0:Exit):"); scanf("%d",&choice); switch(choice) { case 0: exit(1); break; case 1: printf("Enter an element to insert:"); scanf("%d",&x); insert(QUEUE,x); break; case 2: display(QUEUE); break; case 3: delete(QUEUE); break; default: printf("nInvalid choicen"); break; } } return 0;
  • 24.
    APPLICATIONS OF QUEUE •Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive i.e First come first served. • Implementation of BFS in Trees & Graphs • In networks, there are mail queues and queues in routers/switches. • In operating systems, queues are used in Semaphores, Spooling in printers, FCFS (First come First serve) scheduling, Buffer for devices like keyboards. • In the case of transferring the data asynchronously (i.e. it is not necessary to receive and send the data at the same rate) between two processes. For example, IO Buffers, pipes, file IO, etc • In real life scenario, Call Center phone systems uses Queues to hold people calling them in an order, until a service representative is free.