Subject Name DATA STURCTURES WITH C Subject Code
Subject Name: DATA STURCTURES WITH C Subject Code: 10 CS 35 Prepared By: AMBIKA NITHENDRA MAHAJAN Department: ISE Date: 12/08/14 10/26/2021
CHAPTER 3 STACKS AND QUEUES Two of the more common data objects found in computer algorithms are stacks and queues. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. The restrictions on a stack imply that if the elements A, B, C, D, E are added to the stack, in that order, then the first element to be removed/deleted must be E. Equivalently we say that the last"element to be inserted into the stack will be the first to be removed. For this reason stacks are sometimes referred to as Last In First Out (LIFO) lists. illustration E top D C C top C B B B top B A A top A A A 10/26/2021 Inserting and deleting elements in a stack D top C B A
Some stack applications • Implementing recursive calls • Expression evaluation - evaluation of postfix expression • Conversion of expressions – Infix to postfix – Postfix to infix • Maze problem • Breadth First Search 10/26/2021
Abstract data type for stack structure Stack objects: a finite ordered list with zero or more elements. functions: for all stack Stack, item element, max_stack_size positive integer Stack Create. S(max_stack_size) : : = create an empty stack whose maximum size is max_stack_size Boolean Is. Full(stack, max_stack_size) : : = if (number of elements in stack == max_stack_size) return TRUE else return FALSE Stack Add(stack, item) : : = if (Is. Full(stack)) stack_full else insert item into top of stack and return 10/26/2021
Boolean Is. Empty(stack) : : = if(stack == Create. S(max_stack_size)) return TRUE else return FALSE Element Delete(stack) : : = if(Is. Empty(stack)) return else remove and return the item on the top of the stack. 10/26/2021 ADT : Abstract data type Stack
Array-based Stack Implementation Allocate an array of some size (pre-defined) Maximum N elements in stack Bottom stack element stored at element 0 last index in the array is the top Increment top when one element is pushed, decrement after pop 10/26/2021
Implementation: using array Stack Create. S(max_stack_size) : : = #define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; Boolean Is. Empty(Stack) : : = top< 0; Boolean Is. Full(Stack) : : = top >= MAX_STACK_SIZE-1; 10/26/2021
Push operation void push(int *top, element item) { if (*top >= MAX_STACK_SIZE-1) { stack_full( ); return; } stack[++*top] = item; } program : Add to a stack. 10/26/2021
Pop operation element pop(int *top) { if (*top == -1) return stack_empty( ); /* returns and error key */ return stack[(*top)--]; } Program : Delete from a stack. 10/26/2021
Queue (Queue: a First-In-First-Out (FIFO) list) • Queue is an ordered list in which all insertions take place at one end, the rear, while all deletions take place at the other end, the front. • The restrictions on a queue require that the first element which is inserted into the queue will be the first one to be removed. Thus A is the first letter to be removed, and queues are known as First In First Out (FIFO) lists. • The first element inserted is the first one to be removed • The most common occurrence of a queue in computer applications is for the scheduling of jobs • The first one in line is the first one to be served 10/26/2021
Real life examples Waiting in line Ticket Counter Applications related to Computer Science Threads Job scheduling (e. g. Round-Robin algorithm for CPU allocation) Queue: a First-In-First-Out (FIFO) list 10/26/2021
Abstract data type of queue structure Queue objects: a finite ordered list with zero or more elements. functions: for all queue Queue, item element, max_ queue_ size positive integer Queue Create. Q(max_queue_size) : : = create an empty queue whose maximum size is max_queue_size Boolean Is. Full. Q(queue, max_queue_size) : : = if(number of elements in queue == max_queue_size) return TRUE else return FALSE Queue Add. Q(queue, item) : : = Is. Full. Q(queue)) queue_full else insert item at rear of queue and return queue Boolean Is. Empty. Q(queue) : : = if (queue ==Create. Q(max_queue_size)) return TRUE else return FALSE Element Delete. Q(queue) : : = if (Is. Empty. Q(queue)) return else remove and return the item at front of queue. 10/26/2021
Implementation 1: using array Queue Create. Q(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 Is. Empty(queue) : : = front == rear Boolean Is. Full. Q(queue) : = rear == MAX_QUEUE_SIZE-1 10/26/2021
Insert operation void addq(int *rear, element item) { /* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE_1) { queue_full( ); return; } queue [++*rear] = item; } 10/26/2021
Delete from a queue Implementation 2: element deleteq(int *front, int rear) { an array as a circular queue Regard /* remove element at the front of • A the morequeue efficient */ queue representation is obtained by regarding the array Q(1: n) if as(circular. *front == rear) • It now becomes more convenient to declare the array as Q(0: n - 1). return queue_empty( ); /* • When rear = n - 1, the next element is entered at Q(0) in case that spot is free. return an error key • front will always point one*/position counterclockwise from the first element in return queue [++ *front]; the queue • front: } one position counterclockwise from the first element rear: 10/26/2021 current end
Figure : Empty and nonempty circular queues 10/26/2021
Problem: one space is left when queue is full Figure : Full circular queues and then we remove the item 10/26/2021
Add to a circular queue void addq (int front, int *rear, element item) { *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) /* reset rear and print error */ return; } queue[*rear] = item; } 10/26/2021
Delete from a circular queue element deleteq(int* front, int rear) { element item; if (*front == rear) return queue_empty( ); /* queue_empty returns an error key */ * front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front]; } 10/26/2021
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. 10/26/2021
• 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. 10/26/2021
A Mazing Problem Figure : An example maze 10/26/2021
Representation A Mazing Problem 10/26/2021 Figure : Allowable moves
Implementation A Mazing Problem typedef struct { short int vert; short int horiz; } offsets; offsets move[8]; /*array of moves for each direction*/ 10/26/2021
Use stack to keep 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]; 10/26/2021
Initialize a stack to the maze’s entrance coordinates and direction to north while (stack is not empty) { /* move to position at top of stack */ <row, col, dir> = delete from top of stack; while (there are moves from current position) { <next_row, next_col > = coordinates of next move; dir = direction of move; if ((next_row == EXIT_ROW)&& (next_col == EXIT_COL)) success; if (maze[next_row][next_col] == 0 && mark[next_row][next_col] == 0) { 10/26/2021
/* legal move and haven’t been there */ mark[next_row][next_col] = 1; /* save current position and direction */ add <row, col, dir> to the top of the stack; row = next_row; col = next_col; dir = north; } } } printf (“No path foundn”); Program : Initial maze algorithm 10/26/2021
Figure : Simple maze with a long path 10/26/2021
Maze search function void path (void) { /* output a path through the maze if such a path exists */ int i, row, col, next_row, next_col, dir, found = FALSE; element position; mark[1][1] = 1; top =0; stack[0]. row = 1; stack[0]. col = 1; stack[0]. dir = 1; while (top > -1 && !found) { position = delete(&top); row = position. row; col = position. col; dir = position. dir; while (dir < 8 && !found) { /*move in direction dir */ next_row = row + move[dir]. vert; next_col = col + move[dir]. horiz; 10/26/2021 0 7 N 1 6 W E 2 5 S 3 4
if (next_row==EXIT_ROW && next_col==EXIT_COL) found = TRUE; else if ( !maze[next_row][next_col] && !mark[next_row][next_col] { mark[next_row][next_col] = 1; position. row = row; position. col = col; position. dir = ++dir; add(&top, position); row = next_row; col = next_col; dir = 0; } else ++dir; } } 10/26/2021
if (found) { printf(“The path is : n”); printf(“row coln”); for (i = 0; i <= top; i++) printf(“ %2 d%5 d”, stack[i]. row, stack[i]. col); printf(“%2 d%5 dn”, row, col); printf(“%2 d%5 dn”, EXIT_ROW, EXIT_COL); } else printf(“The maze does not have a pathn”); } Program : Maze search function 10/26/2021
Evaluation of Expressions • An expression is made up of operands, operators and delimiters. X=a/b-c+d*e-a*c a = 4, b = c = 2, d = e = 3 Interpretation 1: ((4/2)-2)+(3*3)-(4*2)=0 + 8+9=1 Interpretation 2: (4/(2 -2+3))*(3 -4)*2=(4/3)*(-1)*2=-2. 66666… • The first problem with understanding the meaning of an expression is to decide in what order the operations are carried out. • To fix the order of evaluation, we assign to each operator a priority. Then within any pair of parentheses we understand that operators with the highest priority will be evaluated first. 10/26/2021
10/26/2021
10/26/2021
Figure : Precedence hierarchy for C 10/26/2021
Figure : Infix and postfix notation 10/26/2021
10/26/2021 Figure : Postfix evaluation
Algorithm to convert infix To postfix #define MAX_STACK_SIZE 100 /* maximum stack size */ #define MAX_EXPR_SIZE 100 /* max size of expression */ typedef enum{1 paran, rparen, plus, minus, times, divide, mod, eos, operand} precedence; int stack[MAX_STACK_SIZE]; /* global stack */ char expr[MAX_EXPR_SIZE]; /* input string */ 10/26/2021
Int eval(void) { /* evaluate a postfix expression, expr, maintained as a global variable, ‘ ’ is the end of the expression. The stack and top of the stack are global variables. get_token is used to return the token type and the character symbol. Operands are assumed to be single character digits */ precedence token; char symbol; int op 1, op 2; int n = 0; /* counter for the expression string */ int top = -1; token = get_token(&symbol, &n); while (token != eos) { if (token == operand) add(&top, symbol-’ 0’); /* stack insert */ 10/26/2021
else { /* remove two operands, perform operation, and return result to the stack */ op 2 = delete(&top); /* stack delete */ op 1 = delete(&top); switch(token) { case plus: add(&top, op 1+op 2); break; case minus: add(&top, op 1 -op 2); break; case times: add(&top, op 1*op 2); break; case divide: add(&top, op 1/op 2); break; case mod: add(&top, op 1%op 2); } } token = get_token (&symbol, &n); } return delete(&top); /* return result */ } 10/26/2021
precedence get_token(char *symbol, int *n) { /* get the next token, symbol is the character representation, which is returned, the token is represented by its enumerated value, which is returned in the function name */ *symbol =expr[(*n)++]; switch (*symbol) { case ‘(‘ : return lparen; case ’)’ : return rparen; case ‘+’: return plus; case ‘-’ : return minus; 10/26/2021
case ‘/’ : return divide; case ‘*’ : return times; case ‘%’ : return mod; case ‘ ‘ : return eos; default : return operand; /* no error checking, default is operand */ } } 10/26/2021
Infix to Postfix Conversion 10/26/2021 (1) Fully parenthesize expression a / b - c + d * e - a * c --> ((((a / b) - c) + (d * e)) - a * c)) (2) All operators replace their corresponding right parentheses. ((((a / b) - c) + (d * e)) - a * c)) (3) Delete all parentheses. ab/c-de*+ac*-
The orders of operands in infix and postfix are the same. a + b * c, * > + Figure : Translation of a+b*c to postfix 10/26/2021
Rules (1)Operators areoperands taken out ofinthe stackand as long as their The orders of infix postfix arein-stack the same. precedence(isp) is higher than or equal to the incoming precedence (icp)of a + b * c, * > + the new operator. (2)’(‘ has low in-stack precedence, and high incoming precedence. • 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 store them in a stack until just the right moment and then to unstack and pass them to the output. 10/26/2021
Function to convert from infix to postfix void postfix(void) { /* output the postfix of the expression. The expression string, the stack, and top are global */ char symbol; precedence token; int n = 0; int top = 0; /* place eos on stack */ 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 ){ 10/26/2021
/*unstack tokens until left parenthesis */ while (stack[top] != lparen) print_token(delete(&top)); delete(&top); /*discard the left parenthesis */ } else{ /* remove and print symbols whose isp is greater than or equal to the current token’s icp */ while(isp[stack[top]] >= icp[token] ) print_token(delete(&top)); add(&top, token); } } while ((token = delete(&top)) != eos) print_token(token); print(“n”); } 10/26/2021
Figure : Infix and postfix expressions 10/26/2021
Multiple stacks and queues Two stacks m[0], m[1], …, m[n-2], m[n-1] bottommost stack 1 More than two stacks (n) memory is divided into n equal segments boundary[stack_no] 0 stack_no < MAX_STACKS top[stack_no] 0 stack_no < MAX_STACKS 10/26/2021 bottommost stack 2
Initial configuration for n stacks in memory Initially, boundary[i]=top[i]. 0 1 boundary[ 0] top[ 0] [ m/n ] boundary[1] top[ 1] 2[ m/n ] boundary[ 2] top[ 2] m-1 boundary[n] All stacks are empty and divided into roughly equal segments. 10/26/2021
#define MEMORY_SIZE 100 /* size of memory */ #define MAX_STACK_SIZE 100 /* max number of stacks plus 1 */ /* global memory declaration */ element memory[MEMORY_SIZE]; int top[MAX_STACKS]; int boundary[MAX_STACKS]; int n; /* number of stacks entered by the user */ top[0] = boundary[0] = -1; for (i = 1; i < n; i++) top[i] =boundary[i] =(MEMORY_SIZE/n)*i; boundary[n] = MEMORY_SIZE-1; 10/26/2021
void add(int i, element item) { /* add an item to the ith stack */ if (top[i] == boundary [i+1]) stack_full(i); may have unused storage memory[++top[i]] = item; } Program : Add an item to the stack-no element delete(int i) { /* remove top element from the ith stack */ if (top[i] == boundary[i]) return stack_empty(i); return memory[top[i]--]; } Program : Delete an item from the stack-no 10/26/2021
Find j, stack_no < j < n or, 0 j < stack_no b[0] t[0] b[1] t[1] such that top[j] < boundary[j+1] b[i] t[i+1] b[i+2] t[j] b[j+1] b[n] b=boundary, t=top Figure : Configuration when stack i meets stack i+1, but the memory is not full 10/26/2021
References • Text Book “Fundamentals of Data Structures in c” by Sahni, 2 nd edition. 10/26/2021
- Slides: 54