0% found this document useful (0 votes)
9 views

Stacks&Queues Lecture 4

Uploaded by

Segni WM
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Stacks&Queues Lecture 4

Uploaded by

Segni WM
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Lecture 4

Stack & Queue

2023 Stacks 1
Today’s discussion…

*Stack • Queue
* Basic principles * Basic principles
* Operation of stack * Operation of queue
* Stack using Array * Queue using Array
* Stack using Linked List * Queue using Linked List
* Applications of stack * Applications of queue

2023 Stacks 2
Stack

2023 Stacks 3
Basic Idea
• A stack is an Abstract Data Type (ADT),
commonly used in most programming
languages. It is named stack as it behaves like a
real-world stack, for example – a deck of cards
or a pile of plates, etc.

2023 Stacks 4
Stack Representation

• Can be implemented by means of Array, Structure,


Pointers and Linked List.
• Stack can either be a fixed size or dynamic.
2023 Stacks 5
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
/* Check if stack is full */

2023 Stacks 6
Stack using Array

2023 Stacks 7
Push Operation
• The push operation is used to insert an element in to the stack.
• The new element is added at the topmost position of the stack.
• First check if TOP==MAX-1.
If true, then it means the stack is full and no more insertions can
further be added, an OVERFLOW message is printed.
• If not true, increase TOP by 1, then add the element at TOP position

A B C D E

0 1 2 3 TOP = 4 5 6 7 8 9

A B C D E F

0 1 2 3 4 TOP =5 6 7 8 9
Pop Operation
• The pop operation is used to delete the topmost element from the
stack.
• First check if TOP == -1.
If true then it means the stack is empty so no more deletions can
further be done, an UNDERFLOW message is printed.
If not true, get the value of the top element, decrease TOP by one.

A B C D E

0 1 2 3 TOP = 4 5 6 7 8 9

A B C D

0 1 2 TOP = 3 4 5 6 7 8 9
Peek Operation
• Peek is an operation that returns the value of the topmost
element of the stack without deleting it from the stack.
• The peek operation first checks if the stack is empty or contains
some elements.
• If TOP == -1, then an appropriate message is printed else the
value is returned.
A B C D E

0 1 2 3 TOP = 4 5 6 7 8 9

Here Peek operation will return E, as it is the value of the


topmost element of the stack.
Algorithms for Push and Pop Operations
Algorithm to PUSH an element in a stack
Step 1: IF TOP = MAX-1, then
PRINT “OVERFLOW”
Goto Step 4
[END OF IF]
Step 2: SET TOP = TOP + 1
Step 3: SET STACK[TOP] = VALUE
Step 4: END

Algorithm to POP an element from a stack


Step 1: IF TOP = NULL, then
PRINT “UNDERFLOW”
Goto Step 4
[END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP - 1
Step 4: END
Algorithm for Peek Operation

Algorithm for Peep Operation

Step 1: IF TOP = NULL, then


PRINT “STACK IS EMPTY”
Go TO Step 3
[END OF IF]
Step 2: RETURN STACK[TOP]
Step 3: END
Stack using Linked List

2023 Stacks 13
Push using Linked List
Algorithm to PUSH an element in a linked stack
Step 1: Allocate memory for the new node and name it as New_Node
Step 2: SET New_Node->DATA = VAL
Step 3: IF TOP = NULL, then
SET New_Node->NEXT = NULL
SET TOP = New_Node
ELSE
SET New_node->NEXT = TOP
SET TOP = New_Node
[END OF IF]
Step 4: END

top

2023 Stacks 14
Pop using Linked List
Algorithm to POP an element from a stack

Step 1: IF TOP = NULL, then


PRINT “UNDERFLOW”
Goto Step 5
ELSE
Step 2: SET PTR = TOP
Step 3: SET TOP = TOP ->NEXT
Step 4: FREE PTR
Step 5: END

top

2023 Stacks 15
Basic Idea

• In the array implementation, we would:


• Declare an array of fixed size (which determines the maximum
size of the stack).

• Keep a variable which always points to the “top” of the stack.


• Contains the array index of the “top” element.

• In the linked list implementation, we would:


• Maintain the stack as a linked list.
• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.

2023 Stacks 16
Declaration

#define MAXSIZE 100 struct lifo


{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST

2023 Stacks 17
Stack Creation

void create (stack *s) void create (stack **top)


{ {
s->top = -1; *top = NULL;
/* s->top points to /* top points to NULL,
last element indicating empty
pushed in; stack */
initially -1 */ }
}

ARRAY LINKED LIST

2023 Stacks 18
Pushing an element into stack

void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}

ARRAY LINKED LIST

2023 Stacks 19
Popping an element from stack

int pop (stack **top)


{
int pop (stack *s) int t;
{ stack *p;
if (s->top == -1)
if (*top == NULL)
{ {
printf (“\n Stack underflow”); printf (“\n Stack is empty”);
exit(-1); exit(-1);
} }
else
else {
{ p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
return t;
} }
}

ARRAY LINKED LIST

2023 Stacks 20
Checking for stack empty

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

2023 Stacks 21
Applications of Stacks
1. Reversing a list
2. Page-visited history in a Web browser
3. Undo sequence in a text editor
4. Parentheses checker
5. Conversion of an infix expression into a postfix
expression and evaluation of a postfix expression
6. Conversion of an infix expression into a prefix expression
and evaluation of a postfix expression
7. Recursion

2023 Stacks 22
Infix and Postfix Notations
• Infix: operators placed between operands:
A+B*C
• Postfix: operands appear before their operators:-
ABC*+
Rule in precedence order
{}[]()
^ R-L
/* L-R
+- L-R

2023 Stacks 23
Infix to Postfix
Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+

A + B * C  (A + (B * C))  (A + (B C *) )  A B C * +

A + B * C + D  ((A + (B * C)) + D )  ((A + (B C*) )+ D) 


((A B C *+) + D)  A B C * + D +

2023 Stacks 24
Infix to postfix conversion
• Use a stack for processing operators (push and pop
operations).
• Scan the sequence of operators and operands from
left to right and perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains
operator of a lower precedence and push the present
operator.

2023 Stacks 25
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators
until you see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the
stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association.
If the association is left to right, pop and print the top of the stack and then push the
incoming operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack,
pop the stack and print the top operator. Then test the incoming operator against the
new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)

2023 Stacks 26
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E 2 * * A
3 ( *( A
becomes
4 B *( AB
ABCD*+*E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
is also called as 9 ) * ABCD*+
Reverse Polish 10 + + ABCD*+*
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+

2023 Stacks 27
Evaluation of Postfix Expressions
• Easy to do with a stack
• given a proper postfix expression:
– get the next token
– if it is an operand push it onto the stack
– else if it is an operator
• pop the stack for the right hand operand
• pop the stack for the left hand operand
• apply the operator to the two operands
• push the result onto the stack
– when the expression has been exhausted the result is
the top (and only element) of the stack
2023 Stacks 28
Prefix Notation
• In a prefix notation, the operator is placed before the operands.
• For example, if A+B is an expression in infix notation, then the
corresponding expression in prefix notation is given by +AB.
• While evaluating a prefix expression, the operators are applied to
the operands that are present immediately on the right of the
operator.
• Prefix expressions also do not follow the rules of operator
precedence, associativity, and even brackets cannot alter the order
of evaluation.
• The expression (A + B) * C is written as:
• *+ABC in the prefix notation

2023 Stacks 29
Convert Infix Expression into Prefix Expression

• Consider an infix expression: (A – B / C) * (A / K – L)


• Step 1: Reverse the infix string. Note that while reversing the string
you must interchange left and right parenthesis.
• (L – K / A) * (C / B – A)
• Step 2: Obtain the corresponding postfix expression of the infix
expression obtained as a result of Step 1.
• The expression is: (L – K / A) * (C / B – A)
• Therefore, [L – (K A /)] * [ (C B /) - A ]
• = [LKA/-] * [ CB/A-]
• =LKA/-CB/A-*
• Step 3: Reverse the postfix expression to get the prefix expression
• Therefore, the prefix expression is * - A / B C - / A K L

2023 Stacks 30
Queue

2023 Stacks 31
Concept of queue
• Queue is a data structure which stores its elements in an
linearly ordered manner. Inserting element at one end
(rear) and deleting element from another end (front).
• A queue is a FIFO (First-In, First-Out) data structure in
which the element that is inserted first is the first one to
be taken out.
• The term queue comes from the analogy that people are
in queue waiting for services. First come, First served
(FCFS)
Conceptual View of a Queue
Adding an element

Front of queue

New element is added


to the rear of the queue

6-33
Conceptual View of a Queue
Removing an element

New front element of queue

Element is removed
from the front of the
queue
6-34
Queue operations

Queue implementations
• using an array
• using a linked list
QUEUE: First-In-First-Out (LIFO)
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */

Assumption: queue contains integer elements!

2023 Stacks 36
Queue using Array & Linked List

2023 Stacks 37
Array Representation of Queues
• Queues can be easily represented using arrays.
• Every queue has front and rear variables that point to the position
from where deletions and insertions can be done, respectively.
• Consider the queue shown in figure Enqueue(12)
Enqueue(9)
12 9 7 18 14 36 Enqueue(7)
Enqueue(18)
Front 0 1 2 3 4 5 6 7 8 9
Enqueue(14)
• Here, front = 0 and rear = 5. Rear
Enqueue(36)

• If we want to add one more value in the list say with value 45, then
rear would be incremented by 1 and the value would be stored at the
position pointed by rear. Enqueue(45)

12 9 7 18 14 36 45

0 1 2 3 4 5 6 7 8 9
Front
Rear
Array Representation of Queues
• Now, front = 0 and rear = 6. Every time a new element has to be
added, we will repeat the same procedure.

• Now, if we want to delete an element from the queue, then the


value of front will be incremented. Deletions are done from only
this end of the queue.
dequeue()

9 7 18 14 36 45

Front 0 1 2 3 4 5 6 7 8 9

• Now, front = 1 and rear = 6. rear


Array Representation of Queues
• Before inserting an element in the queue we must check for
overflow conditions.
• An overflow occurs when we try to insert an element into a queue
that is already full, i.e. when rear = MAX – 1, where MAX specifies
the maximum number of elements that the queue can hold.
• Similarly, before deleting an element from the queue, we must
check for underflow condition.
• An underflow occurs when we try to delete an element from a
queue that is already empty. If front = -1 and rear = -1, this means
there is no element in the queue.
Algorithm for Insertion Operation
Algorithm to insert an element in a queue
Step 1: IF REAR=MAX-1, then;
Write OVERFLOW
Goto Step 4
[END OF IF]
Step 2: ELSE IF FRONT == -1 and REAR == -1, then
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
Step 3: SET QUEUE[REAR] = NUM
Step 4: Exit

Time complexity: O(1)


Algorithm for Deletion Operation

Algorithm to delete an element from a queue


Step 1: IF FRONT = -1 OR FRONT > REAR, then
Write UNDERFLOW
Goto Step 2
ELSE
SET FRONT = FRONT + 1
[END OF IF]
Step 2: Exit

Time complexity: O(1)


Problem With Array Implementation
• The size of the queue depends on the number
and order of enqueue and dequeue.
• It may be situation where memory is available
but enqueue is not possible.
Effective
0 queuing storage area of array gets
N reduced.
DEQUEUE ENQUEUE

front
front rearrear

Use of circular array indexing


2023 Stacks 43
Circular Queues
7 18 14 36 45 21 99 72

0 1 2 3 4 5 6 7 8 9
front rear
• We will explain the concept of circular queues using an example.
• In this queue, front = 2 and rear = 9.
• Now, if you want to insert a new element, it cannot be done
because the space is available only at the left of the queue.
• If rear = MAX – 1, then OVERFLOW condition exists.
• This is the major drawback of an array queue. Even if space is
available, no insertions can be done once rear is equal to MAX – 1.
• This leads to wastage of space. In order to overcome this problem,
we use circular queues.
• In a circular queue, the first index comes right after the last index.
• A circular queue is full, only when front=0 and rear = Max – 1.
Inserting an Element in a Circular Queue
• For insertion we check for three conditions which are as follows:
 If front=0 and rear= MAX – 1, then the circular queue is full.
90 49 7 18 14 36 45 21 99 72

front=0 1 2 3 4 5 6 7 8 rear = 9

 If rear != MAX – 1, then the rear will be incremented and value will
be inserted
90 49 7 18 14 36 45 21 99

front=0 1 2 3 4 5 6 7 rear= 8 9

• If front!=0 and rear=MAX -1, then it means that the queue is


not full. So, set rear = 0 and insert the new element.

49 7 18 14 36 45 21 99 72

front=1 2 3 4 5 6 7 8 rear= 9
Inserting an Element in a Circular Queue

• rear = front -1 overflow

9 10 7 18 14 36 45 21 99 72

rear=1 front=2 3 4 5 6 7 8 9
Algorithm to Insert an Element in a
Circular Queue
Step 1: IF FRONT=0 and REAR=MAX–1, or REAR = FRONT – 1 then
Write “OVERFLOW”
Goto Step 4
[END OF IF]

Step 2: IF FRONT = -1 and REAR = -1, then;


SET FRONT = REAR = 0
ELSE IF REAR = MAX – 1 and FRONT != 0
SET REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: Exit
Deleting an Element from a Circular Queue
• To delete an element again we will check for three conditions:
 If front = -1, then it means there are no elements in the queue. So
an underflow condition will be reported.

0 1 2 3 4 5 6 7 8 9

 If the queue is not empty and after returning the value on front, if
front = rear, then it means now the queue has become empty and
so front and rear are set to -1.
Delete this element and set
81
rear = front = -1

0 1 2 3 4 5 6 7 8 front=rear= 9

 If the queue is not empty and after returning the value on front, if
front = MAX -1, then front is set to 0.
72 63 9 18 27 39 81

0 1 2 3 4 rear= 5 6 7 8 front= 9
Algorithm to Delete an Element from a
Circular Queue
Step 1: IF FRONT = -1, then
Write “Underflow”
Goto Step 4
[END OF IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END OF IF]
[END OF IF]
Step 4: EXIT
Queue implimentation using Linked List
• Basic idea:
• Create a linked list to which items would be added to one end
and deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted). Rear

Front DELETION INSERTION


2023 Stacks 50
Inserting an Element in a Linked Queue
Algorithm to insert an element in a linked queue

Step 1: Allocate memory for the new node and


name the pointer as PTR
Step 2: SET PTR->DATA = VAL
Step 3: IF FRONT = NULL, then
SET FRONT = REAR = PTR
SET FRONT->NEXT = REAR->NEXT = NULL
ELSE
SET REAR->NEXT = PTR
SET REAR = PTR
SET REAR->NEXT = NULL
[END OF IF]
Step 4: END

Time complexity: O(1)


Queue: Linked List Structure

ENQUEUE

front rear

2023 Stacks 52
Deleting an Element from a Linked Queue

Algorithm to delete an element from a


linked queue

Step 1: IF FRONT = NULL, then


Write “Underflow”
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: FRONT = FRONT->NEXT
Step 4: FREE PTR
Step 5: END

Time complexity: O(1)


Queue: Linked List Structure

DEQUEUE

front rear

2023 Stacks 54
Example :Queue using Linked List
#include < stdio.h >
#include < stdlib.h >

struct node {
int data;
struct node * next;
};

struct node * front;


struct node * rear;

void insert(struct node * ptr, int item) {

ptr = (struct node * ) malloc(sizeof(struct node));


if (ptr == NULL) {
printf("\nOVERFLOW\n");

2023 Stacks 55
Cont.
return;
} else {
ptr - > data = item;
if (front == NULL) {
front = ptr;
rear = ptr;
front - > next = NULL;
rear - > next = NULL;
} else {
rear - > next = ptr;
rear = ptr;
rear - > next = NULL;
}
}
}

2023 Stacks 56
Cont.
void deleteNode(struct node * ptr) {
if (front == NULL) {
printf("Underflow");
return;
} else {
ptr = front;
front = front - > next;
free(ptr);
}
}

2023 Stacks 57
Cont.
int main() {
struct node * head = NULL;
insert(head, 10);
insert(head, 20);

printf("front element: %d\n", front - > data);


deleteNode(head);
printf("front element: %d", front - > data);
return 0;
}

2023 Stacks 58
Applications of Queues

• Waiting lists
• Access to shared resources (e.g., printer)
• Multiprogramming

2023 Stacks 59
Assignment #3
• Tower of Hanoi using Stack ADT.
• Implement Queue using Stack.
• Implementation of Deque Operation using
Circular Array.

2023 Stacks 60

You might also like