Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is.

Similar presentations


Presentation on theme: "Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is."— Presentation transcript:

1 Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is an ordered-list in which all the insertions and deletions are made at one end to maintain the LIFO order. (Stack is LIFO data structure)‏ Race(Dhiyad901@gmail.com)

2

3 Stacks The operations defined on a stack are: Push-Store onto a stack Pop-retrieve from stack Top-examine the top element in the stack Is_empty-check if the stack is empty Is_Full-check if the stack is full A stack can be very easily implemented using arrays. Can also be implemented using linked list Stack is implemented by maintaining a pointer to the top element in the stack. This pointer is called the stack pointer. Linked implementation will be discussed later. Race(Dhiyad901@gmail.com)

4 Stacks – Array Implementation If a stack is implemented using arrays, the following two conventions can be used: A stack can grow upwards, i.e., from index 0 to the maximum index, or it can grow downwards, i.e., from the maximum index to index 0. Stack pointer can point to the last element inserted into the stack or it can point to the next available position. Race(Dhiyad901@gmail.com)

5 6 8 3 12 6 5 4 3 2 1 0 7 8 9 Growing Downwards Initial state: stk_ptr = MAX - 1 stk_ptr points to the next empty location Pop – first increment stk_ptr and then take data out Push – first add data to the stack, then decrement stk_ptr Race(Dhiyad901@gmail.com)

6 6 8 3 12 6 5 4 3 2 1 0 7 8 9 Growing Downwards Initial state: stk_ptr = MAX stk_ptr points to the last element added to the stack Pop – first take data out and then increment stk_ptr Push – first decrement the stk_ptr and then add data Race(Dhiyad901@gmail.com)

7 6 4 5 2 7 6 5 4 3 2 1 0 7 8 9 Growing Upwards Initial state: stk_ptr = 0 Push – first add data to the stack then increment stk_ptr Pop – first decrement stk_ptr and then take data out stk_ptr points to the next empty location Race(Dhiyad901@gmail.com)

8 6 4 5 2 7 6 5 4 3 2 1 0 7 8 9 Growing Upwards Initial state: stk_ptr = -1 Push – first increment the stk_ptr and then add data Pop – first take data out and then decrement stk_ptr stk_ptr points to the last element added to the stack Race(Dhiyad901@gmail.com)

9 Stacks – Array Implementation class Stack { private: int maxSize;// maximum storage capacity int stk_ptr;// stack pointer int *stackArray;// array used to implement stack public: Stack(int s );// constructor ~Stack() {delete [ ] stackArray; } // destructor bool push (int);// add an element to the stack bool pop(int &);// remove an element from stack bool isFull();// check if the stack is full bool isEmpty();// check if the stack is empty }; Race(Dhiyad901@gmail.com)

10 bool Stack::push(int n)‏ { if (! isFull() ) { stackArray[stk_ptr] = n; stk_ptr = stk_ptr + 1; return true; } else return false; } bool Stack::pop(int &n)‏ { if (! IsEmpty ()) { stk_ptr = stk_ptr – 1; n = stackArray[stk_ptr]; return true; } else return false; } bool Stack::isEmpty()‏ { return (stk_ptr == 0); } Stack::Stack(int s)‏ { maxSize = s; stk_ptr = 0; stackArray = new int[maxSize]; } bool Stack::isFull()‏ { return (stk_ptr == maxSize); } Race(Dhiyad901@gmail.com)

11 Applications of stack Is used in recursion Used in expression evaluation Used for string comparisons Used in function calling Used in memory manipulation to store addresses Used in tree manipulation etc. Race(Dhiyad901@gmail.com)

12 Multiple Stack More than one stacks can be implemented on a single one dimensional array Size of each array can be equal or different Number of arrays can be fixed or varying Simple implementation consists of two arrays of. Size of each array can not be predicted Race(Dhiyad901@gmail.com)

13 Queues Queue is a data structure that can be used to store data which can later be retrieved in the first in first out (FIFO) order. Queue is an ordered-list in which all the insertions and deletions are made at two different ends to maintain the FIFO order. The operations defined on a Queue are: Add/ Insert-Store onto a Queue Remove/ Delete-retrieve (delete) from Queue isEmpty-check if the Queue is empty isFull-check if the Queue is full A Queue can be very easily implemented using arrays. Queue is implemented by maintaining one pointer to the front element in the Queue and another pointer pointing to the rear of the Queue. Insertions are made at the rear and deletions are made from the front. Race(Dhiyad901@gmail.com)

14 Uses of Queue Many real life applications ( banks, bill paying in shopping malls, etc ) Process Scheduling Memory Management Trees traversing etc Race(Dhiyad901@gmail.com)

15 Queues – Array Implementation class Queue { public: Queue(int s = 10);// constructor - default size = 10 ~Queue() {delete [ ] QueueArray; } // destructor bool add (int n); bool remove (int &n); bool isFull(){return size == MaxSize;} bool isEmpty() {return size == 0; } private: int maxSize;// max Queue size int front, rear; int *QueueArray; int size;// no. of elements in the Queue }; Race(Dhiyad901@gmail.com)

16 Queue::Queue(int s)‏ { if (s <= 0) maxSize = 10; else maxSize = s; QueueArray = new int[maxSize]; size = 0; rear = 0;// points to the last element front = 0;// points to first element } Race(Dhiyad901@gmail.com)

17 bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; size++; return true; } else return false; } Race(Dhiyad901@gmail.com)

18 bool Queue::remove(int &n)‏ { if (! isEmpty() { n = QueueArray[front]; front++; size--; return true; } else return false; } Race(Dhiyad901@gmail.com)

19 Assume maxSize = 5 Initial condition size = 0; front = 0; rear = 0; Add 3, remove 1 size = 2; front = 1; rear = 3; Race(Dhiyad901@gmail.com)

20 Add 2 more, remove 1 more size = 3; front = 2; rear = 5; Question: Is the Queue Full? Where to add the next element? Push everything back size = 3; front = 0; rear = 3; Cost?O (size)‏ Race(Dhiyad901@gmail.com)

21 Circular Implementation bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } 0 1 2 3 MS-1 Race(Dhiyad901@gmail.com)

22 Circular Implementation bool Queue::remove(int &n)‏ { if (! isEmpty() { n = QueueArray[front]; front++; if (front == maxSize) front = 0; size--; return true; } else return false; } 0 1 2 3 MS-1 Race(Dhiyad901@gmail.com)

23 bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } 0 1 2 3 MS-1 bool Queue::isFull() {return size == MaxSize;} bool Queue::isEmpty() {return size == 0; } Queue::Queue(int s)‏ { if (s <= 0) MaxSize = 10; else MaxSize = s; QueueArray = new int[MaxSize]; size = 0; rear = 0; front = 0; } bool Queue::remove(int &n)‏ { if (! isEmpty() ) { n = QueueArray[rear]; front++; if (front == maxSize) front = 0; size--; return true; } else return false; } Race(Dhiyad901@gmail.com)

24 bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } bool Queue::remove(int &n)‏ { if (! isEmpty() { n = QueueArray[front]; front++; if (front == maxSize) front = 0; size--; return true; } else return false; } 0 1 2 3 MS-1 Add:rear = (rear + 1) % maxSize; Remove:front = (front + 1) % maxSize; What happens if we try to do it clockwise? Race(Dhiyad901@gmail.com)

25 Double Ended Queue (Dequeue) We can insert at or delete from queue at either end Can be used as queue as well as stack Two types - Input restricted dequeue - output restricted dequeue Race(Dhiyad901@gmail.com)

26 Input restricted dequeue (algorithm) remove (queue, n, f, r, side) 1.If (f= -1 or r= -1) then print (“queue is empty”) return (dummy value) 2.If (f = r) then n = queue [f] f = -1, r = -1 3.If (side = ‘front) then n = queue [f] f = f + 1 4.If (side = ‘rear’) then n = queue [r] r = r – 1 5. Return (n) Race(Dhiyad901@gmail.com)

27 Output restricted dequeue (algorithm) Add( queue, f, r, n, size, side) 1. If (side = ‘front’ and f = 0) or (side = ‘rear’ and r = size-1) print (“ queue full”) return 2. If (side = ‘front’) then if ( f = -1) then f = 0, r = 0 else f = f – 1 queue [f] = n 3. If (side = ‘rear’) then r = r + 1 queue [r] = n if (f = -1) then f = 0, r = 0 4. return Race(Dhiyad901@gmail.com)

28 Priority Queue Items are inserted according to priority Priority determines the order in which items exists in the queue Simple example is mail sorting, process control systems Ascending Priority Queue ( queue which remove lowest priority item first) Descending priority Queue (queue which remove highest priority item first) Implementation is like multiple stack i.e more than one queues can exist on a single one dimensional array Race(Dhiyad901@gmail.com)

29 Applications of Stacks Evaluation of Expression Expressions are of three types 1. infix 2. prefix 3. postfix Infix ( a + b * c - d ) Prefix ( - + a * b c d ) Postfix ( a b c * + d - ) Evaluation of expression like a+b/c*(e-g)+h-f*i was a challenging task for compiler writers. It is a problem of parenthesization of the expression according to operator precedence rule. A fully parenthesized expression can be evaluated with the help of a stack. Race(Dhiyad901@gmail.com)

30 Algorithm to Evaluate fully Parenthesized Expressions 1.while (not end of expression) do 1.get next input symbol 2.if input symbol is not “)” push it into the stack 3.else 1.repeat pop the symbol from the stack 2.until you get “(“ 3.apply operators on the operands 4.push the result back into stack 2.end while 3.the top of stack is the answer Race(Dhiyad901@gmail.com)

31 Evaluation of Fully Parenthesized Expression (a+(b/c)) Assuming a=2, b=6, c=3 Pop”(a+2” and evaluate and push the result back 4)‏)‏ Pop”(b/c” and evaluate and push the result back (a+2)‏)‏ Push(a+(b/cc push(a+(b// push(a+(bb push(a+(( push(a++ push(aa Push(( RemarksStackInput Symbol Race(Dhiyad901@gmail.com)

32 Evaluation of Expressions The normal way of writing expressions i’.e., by placing a binary operator in-between its two operands, is called the infix notation. It is not easy to evaluate arithmetic and logic expressions written in infix notation since they must be evaluated according to operator precedence rules. E.g., a+b*c must be evaluated as (a+(b*c)) and not ((a+b)*c). The postfix or Reverse Polish Notation (RPN) is used by the compliers for expression evaluation. In RPN, each operator appears after the operands on which it is applied. This is a parenthesis-free notation. Stacks can be used to convert an expression from its infix form to RPN and then evaluate the expression. Race(Dhiyad901@gmail.com)

33 INFIX and POSTFIX abc/eg+*+h+fi*-a+b/c*(e+g)+h-f*i ab/c-de*+ac*-a/b-c+d*e-a*c ab+cd+*e/f-(a+b)*(c+d)/e-f ab*cd*+a*b+c*d abc*+a+b*c PostfixInfix Race(Dhiyad901@gmail.com)

34 Algorithm to Evaluate Expressions in RPN 1.while (not end of expression) do 1.get next input symbol 2.if input symbol is an operand then push it into the stack 3.else if it is an operator then 1.pop the operands from the stack 2.apply operator on operands 3.push the result back onto the stack 2.End while 3.the top of stack is answer. Race(Dhiyad901@gmail.com)

35 Algorithm to Evaluate Expressions in RPN (a+b)*(c+d)  ab+cd+* Assuming a=2, b=6, c=3, d=-1 Pop 8 and 2 from the stack, multiply, and push the result back. Since this is end of the expression, hence it is the final result. 16* Pop c and d from the stack, add, and push the result back 8 2+ Push8 c dd Push8 cc Pop a and b from the stack, add, and push the result back 8+ Pusha bb Pushaa RemarksStackInput Symbol Race(Dhiyad901@gmail.com)

36 1.Initialize an empty stack of operators 2.While not end of expression do a.Get the next input token b.If token is “(”push “)”pop and display stack element until a left parenthesis is encountered, but do not display it.. An operator: if stack is empty or token has higher precedence than the element at TOS, push Note: “(” has the lowest precedence else then pop from the stack all the operators with precedence higher than or equal to the scanned symbol and display until “(“ is found or an operator with less precedence is found.. An Operand:Display Algorithm for Infix to RPN Conversion Race(Dhiyad901@gmail.com)

37 Converting Infix to RPN (a+b)*(c+d)  ab+cd+* Pop remaining symbols from the stack and display RPN  a b + c d + * End of input Pop till “(” is found and display – RPN  a b + c d + *)‏)‏ Operand – display – RPN  a b + c d * ( +d Push as + has higher precedence than (* ( ++ Operand – display – RPN  a b + c * (c Push* (( Push as stack is empty** Pop till “(” is found and display – RPN  a b + )‏)‏ Operand – display – RPN  a b ( +b Push as + has higher precedence than (( ++ Operand – display – RPN  a (a Push(( RemarksStackInput Symbol Race(Dhiyad901@gmail.com)

38 a+b*c/(d+e)  a b c * d e + / + Pop till “(” is found – RPN  a b c * d e + + /)‏)‏ Pop remaining symbols from the stack and display RPN  a b c * d e + / + End of input Operand – display – RPN  a b c * d e + / ( +e Push as + has higher precedence than (+ / ( ++ Operand – display – RPN  a b c * d + / (d Push+ / (( Pop * and push / as * and / have the same precedence but / has higher precedence than + – RPN  a b c * + // Operand – display – RPN  a b c + *c Push as * has higher precedence than ++ ** Operand – display – RPN  a b +b Push as stack is empty++ Operand – display – RPN  a a RemarksStackInput Symbol Race(Dhiyad901@gmail.com)

39 Use of Stack in the Implementation of Subprograms In a typical program, the subprogram calls are nested. Some of these subprogram calls may be recursive. Address of the next instruction in the calling program must be saved in order to resume the execution from the point of subprogram call. Since the subprogram calls are nested to an arbitrary depth, use of stack is a natural choice to preserve the return address. Race(Dhiyad901@gmail.com)

40 Activation Records An activation record is a data structure which keeps important information about a sub program. In modern languages, whenever a subprogram is called, a new activation record corresponding to the subprogram call is created, and pushed into the stack. The information stored in an activation record includes the address of the next instruction to be executed, and current value of all the local variables and parameters. i.e. the context of a subprogram is stored in the activation record. When the subprogram finishes its execution and returns back to the calling function, its activation record is popped from the stack and destroyed-restoring the context of the calling function. Race(Dhiyad901@gmail.com)

41 Activation Records Race(Dhiyad901@gmail.com)

42 Recursive Functions Recursion is a very powerful algorithm design tool. A subprogram is called recursive if it directly or indirectly calls itself. A recursive program has two parts: The End Condition. The Recursive Step. The end condition specifies where to stop. With each recursive step you should come closer to the end condition. In other words, with a recursive step, you apply the same algorithm on a scaled down problem and its process is repeated until the end of condition is reached. Race(Dhiyad901@gmail.com)

43 Recursion – Some Examples int linear_search (int a[], int from, int to, int key)‏ { if (from <= to) {//end condition if (key == a[from]) return from; //end condition else return linear_search(a, from+1, to, key) //recursive step } else return -1; } Race(Dhiyad901@gmail.com)

44 int binary_search (int a[], int high, int low, int key)‏ { int mid = (high + low)/2; if (high >=low) { if (key == a[mid]) return mid;//end condition else if (key < a[mid])‏ return binary_search(a, mid -1, low, key); //recursive step else return binary_search(a, high, mid + 1, key); //recursive step } else return-1;// end condition } Race(Dhiyad901@gmail.com)

45 How Does Recursion Work Some More Recursive Functions and Their Simulation int factorial (int n)‏ { int temp; if (n<0)return 0;//end condition else if (n <=1)return 1;//end condition else { temp = factorial(n-1);//recursive step return n*temp; } Race(Dhiyad901@gmail.com)

46 Simulation of factorial(4)‏ if (n<0)return 0; else if (n <=1)return 1; else { temp = factorial (n-1); return n*temp; } n = 4 1. 2. 3. 4. n = 3 1. 2. 3. 4. n = 2 1. 2. 3. 4. n = 1 1. 2. return 1 temp = 1 5. return 2*1 1. 2. return 1 temp = 2 5. return 3*2 1. 2. return 1 temp = 6 5. return 4*6 1. 2. return 1 Race(Dhiyad901@gmail.com)

47 Fibonacci Sequence 0,1,1,2,3,5,8,13,… int fibonacci (int n)‏ { int temp1, temp2; if (n<=0) return 0;//end condition else if (n<=2)return 1;//end condition else{ temp1 = fibonacci(n - 1);// recursive step temp2 = fibonacci(n - 2);//recursive step return temp1 + temp2;// same as return fib(N-1)+fib(N-2)‏ } Race(Dhiyad901@gmail.com)

48 Simulation of fibonacci(4)‏ 1.if (n<=0) return 0; else if (n<=2) return 1; else { temp1 = fibonacci(n - 1); temp2 = fibonacci(n - 2); return temp1 + temp2; } n = 2 1. 1.return 1 n = 4 1. 2. 3. n = 3 1. 2. 3. temp1 = 1 4. 1. 2. return 1 n = 1 1. 2. return 1 temp2 = 1 5. return 2 1. 2. return 1 temp1 = 2 4. 1. 2. return 1 n = 2 1. 2. return 1 temp2 = 1 5. return 3 1. 2. return 1 Race(Dhiyad901@gmail.com)

49 Tower of Honoi Invented by French mathematician Lucas in 1880s. In the town of Honoi, monks are playing a game with: –3 diamond needles fixed on a brass plate. –One needle contains 64 pure gold disks of different diameters. –Plates are put on top of each other in the order of their diameters with the largest plate lying at the bottom on the brass plate. Priests are supposed to transfer all the disks from one needle to the other such that: –Only one disk can be moved at a time. –At no time a disk of larger diameter should be put on a disk of smaller diameter. Race(Dhiyad901@gmail.com)

50 FromUsingTo 3 Disks How much time would it take? Estimate….. According to the legend, that will mark the end of time! Race(Dhiyad901@gmail.com)

51 Tower of Honoi Recursive Solution End Condition: Recursive Step: Race(Dhiyad901@gmail.com)

52 Tower of Honoi void TOH (int from, int to, int using, int n)‏ { if (n>0)// end condition – stop when there is // nothing to be moved { TOH (from, using, to, n-1); // recursive step // move n-1 plates from the starting // disk to the auxiliary disk move (to, from); // move the nth disk to the destination TOH (using, to, from, n-1); // recursive step // move n-1 plates from the auxiliary // disk to the destination disk } } Race(Dhiyad901@gmail.com)

53 1.if (n>0) 2.{ TOH (from, using, to, n-1); move (to, from); TOH (using, to, from, n-1); 1.} Simulation of TOH(1, 2, 3, 3)‏ 12 3 from:1, to:2, using:3, n:3 f = 1, t = 2, u = 3, n = 3 statement: 3 f = 1, t = 2, u = 3, n = 1 statement: 3 f = 1, t = 3, u = 2, n = 2 statement: 3 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 1, t = 2, u = 3, n = 1 statement: 4 f = 1, t = 2, u = 3, n = 1 statement: 5 f = 3, t = 2, u = 1, n = 0 statement: 1 f = 1, t = 3, u = 2, n = 2 statement: 4 f = 1, t = 3, u = 2, n = 2 statement: 5 f = 2, t = 3, u = 1, n = 1 statement: 3 f = 2, t = 1, u = 3, n = 0 statement: 1 f = 2, t = 3, u = 1, n = 1 statement: 4 f = 2, t = 3, u = 1, n = 1 statement: 5 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 1, t = 2, u = 3, n = 3 statement: 4 f = 1, t = 2, u = 3, n = 3 statement: 5 f = 3, t = 2, u = 1, n = 2 statement: 3 f = 3, t = 1, u = 2, n = 1 statement: 3 f = 3, t = 2, u = 1, n = 0 statement: 3 f = 3, t = 1, u = 2, n = 1 statement: 4 f = 3, t = 1, u = 2, n = 1 statement: 5 f = 2, t = 1, u = 3, n = 0 statement: 1 f = 3, t = 2, u = 1, n = 2 statement: 4 f = 3, t = 2, u = 1, n = 2 statement: 5 f = 1, t = 2, u = 3, n = 1 statement: 3 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 1, t = 2, u = 3, n = 1 statement: 4 f = 3, t = 2, u = 1, n = 1 statement: 5 f = 1, t = 2, u = 3, n = 0 statement: 5 Race(Dhiyad901@gmail.com)


Download ppt "Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is."

Similar presentations


Ads by Google