Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 1 Data Structures using C
Chapter-3
STACK AND QUEUE
STACK Data Structure:
A stack is an ordered list in which insertions and deletions are made at one end called the top.
o If we add the elements A, B, C, D, E to the stack, in that
order, then E is the first element we delete from the stack
o A stack is also known as a Last-In-First-Out (LIFO) list.
Fig: Insert and Delete Elements in the stack
Primitive Operations on Stack
push
An item is added to a stack i.e. it is pushed onto the stack.
pop
An item is deleted from the stack i.e. it is popped from the stack.
Working of stack:
Stack, which contains max_size number of elements.
The element item is inserted in the stack at the position
top.
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 2
Since the push operation adds elements into a stack, the stack is also called as pushdown list.
If there are no elements in a stack it is considered as
empty stack.
If the size of the stack is full then it is called stack
overflow.
The push operation is not applicable on full stack otherwise an overflow condition occurs.
The pop operation is not applicable on an empty stack otherwise an underflow condition arises.
We need to have a new operation empty(s) that checks whether a stack s is empty or not.
Another operation on a stack is to determine what the top item of the stack is without removing it.
stacktop(s) returns the top element of the stack s.
Stack ADT:
ADT Stack is
objects:
a finite ordered list with zero or more elements.
functions:
for all stack ∈ Stack, item ∈ element, max_stack_size ∈
positive integer
Stack CreateS(max_stack_size) ::=create an empty stack whose maximum size is max_stack_size
Boolean IsFull(stack, max_stack_size) ::=if(number of elements in stack == max_stack_size)
return TRUE
else return FALSE Stack Push(stack, item) ::=if(IsFull(stack))
stack_fullelseinsert iteminto top of stackand returnabstract
BooleanIsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE
else return FALSE ElementPop(stack) ::= if(IsEmpty(stack)) return
Else remove and return the item on the top of the stack.
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 3
Implementation of stack: using array
StackCreateS(max_stack_size)::=#define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct
{
int key;
/* other fields */ } element;
element stack[MAX_STACK_SIZE]; //declaration of structure variable int top = -1;
Boolean IsEmpty(Stack)::= top< 0;
Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE-1;
Add and Item to Stack:
push()
void push(element item) {
/* add an item to the global stack */ if (top >= MAX_STACK_SIZE-1) { stackFull( ); return; } stack[++top] = item; }
Delete an Item to Stack:
pop()
element pop() {
/* return the top element from the stack */ if (top == -1)
return stackEmpty( ); /* returns and error key */ return stack[top--];
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 4
Stack full:
void stackFull() {
fprintf(stderr, “Stack is full, cannot add element”); exit(EXIT_FAILRE);
}
Stack Using Dynamic Arrays:
StackCreateS()::=#define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct
{
int key;
/* other fields */ } element;
element *stack; //declaration of structure variable MALLOC (stack, sizeof(*stack));
int capacity=1; int top= -1;
Boolean IsEmpty(Stack)::= top< 0;
Boolean IsFull(Stack) ::= top >= capacity-1;
Add and Item to Stack:
push()
void push(int *top, element item){
/* add an item to the global stack */ if (*top >= MAX_STACK_SIZE-1) { stackFull( ); return; } stack[++*top] = item; }
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 5
Delete an Item to Stack:
pop()
element pop(int *top) {
/* return the top element from the stack */ if (*top == -1)
return stackEmpty( ); /* returns and error key */ return stack[(*top)--];
}
Stack full:
void stackFull(){
fprintf(stderr, “Stack is full, cannot add element”); exit(EXIT_FAILRE);
}
Queue Data Structure:
A queue is an ordered list in which all insertion take place one end, called the rear and all deletions take place at the opposite end, called the front
If we insert the elements A, B, C, D, E, in that order, then A is the first element we delete from the queue
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 6
Queue ADT:
Structure Queue is
objects:
a finite ordered list with zero or more elements.functions:
for all queue ∈ Queue, item ∈ element, max_ queue_ size ∈ positive
integer
Queue CreateQ(max_queue_size) ::= create an empty queue whose maximum size is max_queue_size Boolean IsFullQ(queue, max_queue_size) ::=
if(number of elements in queue == max_queue_size) return TRUE
else return FALSE
QueueAddQ(queue, item) ::= if(IsFullQ(queue)) queue_full
Else insert item at rear of queue and return queue Boolean IsEmptyQ(queue) ::= if(queue==CreateQ(max_queue_size)) return TRUE
else returnFALSE
ElementDeleteQ(queue) ::=if (IsEmptyQ(queue)) return
Else remove and return the item at front of queue.
Implementation of Queue using Arrays:
Queue CreateQ(max_queue_size) ::=#define MAX_QUEUE_SIZE 100/* Maximum queue size */ typedef struct { int key; /* other fields */ } element; element queue[MAX_QUEUE_SIZE]; int rear = -1; int front = -1;
Boolean IsEmpty(queue) ::= front == rear
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 7
Add an Element to Queue:
void addq(element item) {
/* add an item to the queue */ if (rear == MAX_QUEUE_SIZE-1) queueFull( );
queue [++rear] = item; }
Add an Element to Queue using Pointer:
void addq(int *rear, element item){
/* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE-1) {
queueFull( ); return;
}
queue [++*rear] = item; }
Delete from a Queue:
element deleteq(){
/* remove element at the front of the queue */ if ( front == rear)
return queueEmpty( ); /* return an error key */ return queue [++front];
}
Delete from a Queue using Pointer:
element deleteq(int*front, intrear){
/* remove element at the front of the queue */ if ( *front == rear)
return queueEmpty( ); /* return an error key */ return queue [++ *front];
} queueFull() { printf(“Queue is Full”); return or exit(); } queueFull() { printf(“Queue is Full”); return or exit(); }
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 8
Queue Empty:
IsEmptyQ(queue)
return (front == rear)
Queue Full
IsFullQ(queue)
return rear == (MAX_QUEUE_SIZE-1)
Applications of Queue:
Queues, like stacks, also arise quite naturally in the computer solution of many problems.
Perhaps the most common occurrence of a queue in computer applications is for the scheduling of jobs.
In batch processing the jobs are ''queued-up'' as they are read-in and executed, one after another read-in the order they were
received.
This ignores the possible existence of priorities, in which case there will be one queue for each priority.
When we talk of queues we talk about two distinct ends: the front and the rear.
Additions to the queue take place at the rear. Deletions are made from the front. So, if a job is submitted for execution, it joins at the rear of the job queue.
The job at the front of the queue is the next one to be executed
Solving Job Scheduling Algorithm using Queue data Structure in Operating System:
creation of job queue
- in the operating system which does not use priorities, jobs are processed in the order they enter the system.
front rear Q[0] Q[1] Q[2] Q[3] Comments -1 -1 -1 -1 0 1 -1 0 1 2 2 2 J1 J1 J2 J1 J2 J3 * J2 J3 * * J3 queue is empty job 1 is added job 2 is added job 3 is added job 1 is deleted job 2 is deleted Note: * representing empty
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 9
Problems with normal Queue:
Queue gradually shifts to the right (as shown above in the job scheduling queue)
queue_full(rear==MAX_QUEUE_SIZE-1)
Queue_full does not always mean that there are MAX_QUEUE_SIZE items in queuethere may be empty spaces available
- Solution to save space:
Circular queue
Circular Queues
more efficient queue representation
- Representing the array queue[MAX_QUEUE_SIZE] as circular - Initially front and rear to 0 rather than -1
- The front index always points one position counterclockwise from the first element in the queue
- The rear index points to the current end of the queue
empty queue Non empty Queue
Note: As the element in the queue are getting filled the rear getting incremented, but as the element getting deleted from the queue the front is also incrementing
where we are wasting lots of memory without use of it as shown in the above fig of job scheduling.
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 10
Add to Circular Queue:
void addq(element item) {
/* add an item to the queue */ rear = (rear +1) % MAX_QUEUE_SIZE;
if (front == rear) /* reset rear and print error */ queueFull( ); } queue[rear] = item; } queueFull() {
printf(“Queue is Full”); return or exit(); }
Delete from Circular Queue:
element deleteq(){
element item;
/* remove front element from the queue and put it in item */ if (front == rear)
return queueEmpty( ); /* returns an error key */ front = (front+1) % MAX_QUEUE_SIZE;
return queue[front]; }
queueFull() {
printf(“Queue is Empty”); return or exit(); }
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 11
Add to Circular Queue using Pointers:
void addq(intfront, int*rear, element item) {
/* add an item to the queue */
*rear = (*rear +1) % MAX_QUEUE_SIZE;
if (front == *rear) /* reset rear and print error */ queueFull( );
queue[*rear] = item; }
Delete from Circular Queue using Pointers:
element deleteq(int* front, intrear){
element item;
/* remove front element from the queue and put it in item */ if (*front == rear)
return queueEmpty( ); /* returns an error key */ *front = (*front+1) % MAX_QUEUE_SIZE;
return queue[*front]; }
queueFull() {
printf(“Queue is Empty”); return or exit(); }
Circular Queue using dynamically Allocated Arrays
Suppose that a dynamically allocated array is used to hold the elements. Let capacity be the number of positions in the array queue. To add an element to a full queue, we must first increase the size of this array using the function realloc. As withdynamically allocated stacks, we use array doubling.
However it isn’t sufficient to simply double the array size using realloc.
Consider the full queue as shown in fig (a). This figure shows the queue with seven elements I an array whose capacity is 8. To
visualize array doubling when a circular queue used, it is better to flatten out the array as in fig (b).
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 12 Fig (c) shows the array after doubling by realloc.
To get a proper circular queue configuration, we must slide the elements in the right segment (i.e. element A and B)to the right end of the array as in fig (d).
To get the configuration as in fig (e) we must follow the following method:
1) Create a new array newQueue of twice the capacity.
2) Copy the second segment (i.e. the elements queue[front + 1] till queue[capacity-1])to positions in newQueue beginning at 0. 3) Copy the first segment (i.e. the elements queue[0] till
queue[rear] to position in newQueue beginning at capacity-front-1)
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 13
Code showing Doubling queue capacity:
Void queueFull() {
/* allocate an array with twice the capacity */ element * newQueue;
MALLOC(newQueue, 2*capacity*sizeof(*queue));
/* copy from queue to newQueue*/ int start = (front + 1) % capacity; if(start < 2)
copy(queue+start, queue+start+capacity-1, newQueue ); else
{
copy(queue+start, queue+capacity, newQueue );
copy(queue, queue+rear+1, newQueue+capacity-start ); } /* Switch to newQueue */ front = 2*capacity-1; rear = capacity-2; capacity = capacity * 2; free(queue); queue = newQueue; }
Add a Circular Queue:
void addq(element item){
/* add an item to the queue */ rear = (rear + 1)% capacity; if (front == rear)
queueFull(); queue[rear] = item; }
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 14
A Mazing Problem:
The rat-in-a-maze experiment is a classical one from experimental psychology.
A rat (or mouse) is placed through the door of a large box without a top.
Walls are set up so that movements in most directions are obstructed.
The rat is carefully observed by several scientists as it makes its way through the maze until it eventually reaches the other exit.
There is only one way out, but at the end is a nice hunk of cheese.
The idea is to run the experiment repeatedly until the rat will zip through the maze without taking a single false path. The trials yield his learning curve.
We can write a computer program for getting through a maze and it will probably not be any smarter than the rat on its first try through. It may take many false paths before finding the right one. But the computer can remember the correct path far better than the rat. On its second try it should be able to go right to the end with no false paths taken, so there is no sense re-running the program. Why don't you sit down and try to write this program yourself before you read on and look at our solution. Keep track of how many times you have to go back and correct something. This may give you an idea of your own learning curve as we re-run the experiment throughout the book.
Experiment implementation:
the representation of the maze - Two-dimensional array- Element 0: open path - Element 1: barriers
Let us represent the maze by a two dimensional array,
MAZE(1:m, 1:n), where a value of 1 implies a blocked path, while a 0 means one can walk right on through. We assume that the rat
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 15
With the maze represented as a two dimensional array, the location of the rat in the maze can at any time be described by the row, i, and column, j of its position. Now let us consider the possible moves the rat can make at some point (i,j) in the maze. Figure 3.6 shows the possible moves from any point (i,j).
The position (i,j) is marked by an X. If all the surrounding squares have a 0 then the rat can choose any of these eight squares as its next position. We call these eight directions by the names of the points on a compass north, northeast, east,
southeast, south, southwest, west, and northwest, or N, NE, E, SE, S,SW, W, NW.
Note:
We must be careful here because not every position has eight neighbors.
If (i,j) is on a border where either i = 1 or m, or j = 1 or n, then less than eight and possibly only three neighbors exist. To avoid checking for these border conditions we can surround the maze by a border of ones.
[row][col] which is on border - has only three neighbors
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 16 m * p maze
- requires (m + 2) * (p + 2) array - entrance position: [1][1]
- exit position: [m][p]
Another device which will simplify the problem is to predefine the possible directions to move in a table, MOVE(1:8.1:2), which has the values
Representation in C
typedef struct {
short int vert; short int horiz; } offsets;
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 17 If we are at position, maze[row][col], and we wish to find the position of the next move, maze[row][col], we set:
next_row = row + move[dir].vert; next_col = col + move[dir].horiz;
Initial attempt at a maze traversal algorithm
-dimensional array, mark, to record the maze positions already checked
pass history
#define MAX_STACK_SIZE 100 /*maximum stack size*/ typedef struct
{
short int row; short int col; short int dir; } element;
element stack[MAX_STACK_SIZE];
Maze Search Algorithm:
void path(void){
int i, row, col, nextRow, nextCol, dir, found=FALSE; element position; /* structure variable */
mark[1][1]=1; top=0;
stack[0].row=1; stack[0].col=1; stack[0].dir=1; while(top > -1 && !found)
{
position = pop();
row = position.row; col=position.col; dir = position.dir;
while(dir < 8 && !found)
{ /* move in direction dir*/ nextRow = row + move[dir].vert; nextCol = col + move[col].horiz;
if(nextRow == EXIT_ROW && nextCol == EXIT_COL) found = TRUE;
else if(!maze[nextRow][nextCol] = col && !mark[nextRow][nextCol]) {
mark[nextRow][nextCol] = 1;
position.row = row; position.col = col; position.dir = ++dir;
push(position);
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 18 } else ++ dir; } } if(found) {
printf(“The Path is: ”); printf(“row col”); for(i=0; i<=top; i++)
printf(“%d%d”, stack[i].row, stack[i].col); printf(“%d%d”, row, col);
printf(“%d%d”, EXIT_ROW, EXIT_COL); }
else
printf(“The maze Does not have Path”); }
Evaluating postfix expressions
ssions is known as infix notation
• binary operator in-between its two operands expressions -free notation referred to as postfix Postfix: - no parentheses, - no precedence Infix Postfix 2+3*4 a*b+5 (1+2)*7 a*b/c ((a/(b-c+d))*(e-a)*c a/b-c+d*e-a*c 2 3 4*+ ab*5+ 1 2+7* ab*c/ abc-d+/ea-*c* ab/c-de*+ac*-
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 19
Evaluating postfix expressions is much simpler than the
evaluation of infix expressions:
Before attempting an algorithm to translate expressions from infix to postfix notation, let us make some observations regarding the virtues of postfix notation that enable easy evaluation of expressions.
To begin with, the need for parentheses is eliminated.
Secondly, the priority of the operators is no longer relevant. The expression may be evaluated by making a left to right scan, stacking operands, and evaluating operators using as operands the correct number from the stack and finally placing the result onto the stack.
This evaluation process is much simpler than attempting a direct evaluation from infix notation.
we make a single left-to-right scan of it.
an expression easily by using a stack
Evaluating Postfix Expression:
6 2/3-4 2*+
Token Stack [0] [1] [2] top 6 2 / 3 - 4 2 * + 6 6 2 6/2 6/2 3 6/2-3 6/2-3 4 6/2-3 4 2 6/2-3 4*2 6/2-3+4*2 0 1 0 1 0 1 2 1 0Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 20
Representation
expression
#define MAX_STACK_SIZE 100 /* max stack size */ #define MAX_EXPR_SIZE 100
/* max expression size */ typedef enum
{
lparen, rparen, plus, minus,times, divide, mode, eos, operand } precedence;
int stack[MAX_STACK_SIZE]; /* global stack */ char expr[MAX_EXPR_SIZE]; /* input string */
Function to evaluate a postfix expression
eval()
- if the token is an operand, convert it to number and push to the stack
- otherwise
1) pop two operands from the stack 2) perform the specified operation 3) push the result back on the stack
function to get a token
get_token()
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 21 int eval()
{
precedence token; char symbol;
int op1, op2; int n = 0; int top = -1;
token = get_token(&symbol, &n); while (token != eos)
{ if (token == operand) push(&top, symbol-’0’); else { op2 = pop(&top); op1 = pop(&top); switch (token) {
case plus: push(&top, op1+op2); break; case minus: push(&top, op1-op2); break; case times: push(&top, op1*op2); break; case divide: push(&top, op1/op2); break; case mod: push(&top, op1%op2);
}
} // end of else
token = get_token(&symbol, &n); } // end of while
return pop(&top); }
precedence get_token(char *psymbol, int *pn) {
*psymbol = expr[(*pn)++]; switch (*psymbol)
{
case ‘(‘ : return lparen; case ‘)‘ : return rparen; case ‘+‘ : return plus; case ‘-‘ : return minus; case ‘*‘ : return times; case ‘/‘ : return divide; case ‘%‘ : return mod; case ‘ ‘ : return eos;
default : return operand; /* no error checking */ }
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 22
Converging Infix to Postfix
Different possible algorithms for producing a postfix expression from an infix one
1) Fully parenthesize the expression
2) move all binary operators so that they replace their corresponding right parentheses
3) Delete all parentheses
For eg) a/b-c+d*e-a*c when fully parenthesized it becomes ((((a/b)-c)+(d*e))-a*c))
Perform step-2 and step-3 on the above parenthesized expression we will get
ab/c-de*+ac*-
This procedure is easy to work only by hand but difficult to be done using a computer.
The problem with this as an algorithm is that it
requires two passes:
The first one reads the expression and parenthesizes it while the second actually moves the operators.
As we have already observed, the order of the operands is the
same in infix and postfix.
So as we scan an expression for the first time, we can form the postfix by immediately passing any operands to the output. Then it is just a matter of handling the operators.
The solution is to PUSH them in a stack until just the right moment and then to POP from stack and pass them to the output.
1) Simple expression:
Simple expression a+b*c - yields abc*+ in postfixtoken
Stack
[0] [1] [2]
top
Output
a + b * c eos + + + * + * -1 0 0 1 1 -1 a a ab ab abc abc*+Translation of a+b*c to postfix
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 23
Parenthesized expression
Parentheses make the translation process more difficult - equivalent postfix expression is parenthesis-free expression a*(b+c)*d
- yield abc+*d* in postfix right parenthesis
- pop operators from a stack until left parenthesis is reached
Token
Stack
[0] [1] [2]
top
output
a * ( b + c ) * d eos * * ( * ( * ( + * ( + * * * * -1 0 1 1 2 2 0 0 0 0 a a a ab ab abc abc+ abc+* abc+*d abc+*d*Translation of a*(b+c)*d to postfix
Postfix:- no parenthesis is needed - no precedence is needed
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] 24
Function to concert infix to postfix:
void postfix(void) { char symbol; precedence token; int n = 0; int top = 0; stack[0] = eos;
for (token = get_token(&symbol, &n); token != eos; token = get_token(&symbol, &n))
{
if (token == operand) printf(“%c”, symbol);
else if (token == rparen) {
while (stack[top] != lparen) print_token(pop(&top));
pop(&top); }
else {
while (isp[stack[top]] >= icp[token]) print_token(pop(&top));
push(&top, token); }
}
while ((token = pop(&top)) != eos) print_token(token);
printf(“\n”); }