540 likes | 549 Views
Learn about implementing and managing elements in stacks and queues efficiently in computer algorithms. Explore applications and abstract data types with practical examples.
E N D
Subject Name: DATA STURCTURES WITH C Subject Code: 10CS35 Prepared By: AMBIKA NITHENDRA MAHAJAN Department: ISE Date: 12/08/14
E D C B A top D C B A D C B A top top C B A top B A top A top Inserting and deleting elements in a stack 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
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
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 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 TRUEelse return FALSE Stack Add(stack, item) ::=if (IsFull(stack)) stack_fullelse insert item into top of stack and return
Boolean IsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUEelse return FALSE Element Delete(stack) ::= if(IsEmpty(stack)) returnelse remove and return the item on the top of the stack. 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
Implementation: using array Stack CreateS(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;BooleanIsEmpty(Stack) ::= top< 0;BooleanIsFull(Stack) ::= top >= MAX_STACK_SIZE-1;
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 .
Pop operation element pop(int *top){ if (*top == -1) return stack_empty( ); /* returns and error key */ return stack[(*top)--]; }Program : Delete from a stack .
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
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
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 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 TRUEelse return FALSE Queue AddQ(queue, item) ::=IsFullQ(queue)) queue_full else insert item at rear of queue and return queue Boolean IsEmptyQ(queue) ::= if (queue ==CreateQ(max_queue_size))return TRUEelse return FALSE Element DeleteQ(queue) ::=if (IsEmptyQ(queue)) return else remove and return the item at front of queue.
Implementation 1: using array 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 Boolean IsFullQ(queue) := rear == MAX_QUEUE_SIZE-1
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;}
Delete from a queue • Implementation 2: • Regard an array as a circular queue • A more efficient queue representation is obtained by regarding the array Q(1:n) as circular. • It now becomes more convenient to declare the array as Q(0:n - 1). • When rear = n - 1, the next element is entered at Q(0) in case that spot is free. • front will always point one position counterclockwise from the first element in the queue • front: one position counterclockwise from the first element • rear: current end element deleteq(int *front, int rear){/* remove element at the front of the queue */ if ( *front == rear) return queue_empty( ); /* return an error key */ return queue [++ *front];}
Problem: one space is left when queue is full Figure : Full circular queues and then we remove the item
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; }
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];}
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.
A Mazing Problem Figure : An example maze
Representation A Mazing Problem Figure : Allowable moves
typedefstruct { short intvert; short inthoriz; } offsets;offsets move[8]; /*array of moves for each direction*/ Implementation A Mazing Problem
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];
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 more 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) {
/* 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 found\n”); Program : Initial maze algorithm
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; 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; } }
if (found) { printf(“The path is :\n”); printf(“row col\n”); for (i = 0; i <= top; i++) printf(“ %2d%5d”, stack[i].row, stack[i].col); printf(“%2d%5d\n”, row, col); printf(“%2d%5d\n”, EXIT_ROW, EXIT_COL); } else printf(“The maze does not have a path\n”); } Program :Maze search function
Evaluation of Expressions • An expression is made up of operands, operators and delimiters. • X = a / b - c + d * e - a * ca = 4, b = c = 2, d = e = 3Interpretation 1:((4/2)-2)+(3*3)-(4*2)=0 + 8+9=1Interpretation 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.
#define MAX_STACK_SIZE 100 /* maximum stack size */#define MAX_EXPR_SIZE 100 /* max size of expression */typedef enum{1paran, rparen, plus, minus, times, divide, mod, eos, operand} precedence;int stack[MAX_STACK_SIZE]; /* global stack */char expr[MAX_EXPR_SIZE]; /* input string */ Algorithm to convert infix To postfix
Int eval(void){ /* evaluate a postfix expression, expr, maintained as a global variable, ‘\0’ is the 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 op1, op2; 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 */
else { /* remove two operands, perform operation, and return result to the stack */ op2 = delete(&top); /* stack delete */ op1 = delete(&top); switch(token) { case plus: add(&top, op1+op2); break; case minus: add(&top, op1-op2); break; case times: add(&top, op1*op2); break; case divide: add(&top, op1/op2); break; case mod: add(&top, op1%op2); } } token = get_token (&symbol, &n); } return delete(&top); /* return result */ }
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;
case ‘/’ : return divide; case ‘*’ : return times; case ‘%’ : return mod; case ‘\0‘ : return eos; default : return operand; /* no error checking, default is operand */ }}
Infix to Postfix Conversion (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
Rules • (1)Operators are taken out of the stack as long as their in-stack precedence(isp) is higher than or equal to the incoming precedence (icp)of 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. The orders of operands in infix and postfix are the same. a + b * c, * > +
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 ){ Function to convert from infix to postfix
/*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”);}
Multiple stacks and queues Two stacks m[0], m[1], …, m[n-2], m[n-1] bottommost bottommost stack 1 stack 2 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
Initial configuration for n stacks in memory Initially, boundary[i]=top[i]. 0 1 [ m/n ] 2[ m/n ] m-1 boundary[ 0] boundary[1] boundary[ 2] boundary[n] top[ 0] top[ 1] top[ 2] All stacks are empty and divided into roughly equal segments.