650 likes | 1.5k Views
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).
E N D
Race(Dhiyad901@gmail.com) 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) 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) 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) 12 3 8 6 • Push – first add data to the stack, then decrement stk_ptr Growing DownwardsInitial state: stk_ptr = MAX - 1 9 • stk_ptr points to the next empty location 8 7 6 5 4 3 • Pop – first increment stk_ptr and then take data out 2 1 0
Race(Dhiyad901@gmail.com) • stk_ptr points to the last element added to the stack 9 12 8 3 7 8 6 6 • Push – first decrement the stk_ptr and then add data 5 4 3 • Pop – first take data out and then increment stk_ptr 2 1 0 Growing DownwardsInitial state: stk_ptr = MAX
Race(Dhiyad901@gmail.com) 9 • stk_ptr points to the next empty location 8 7 • Push – first add data to the stack then increment stk_ptr 6 5 4 6 • Pop – first decrement stk_ptr and then take data out 3 4 2 5 1 2 0 7 Growing UpwardsInitial state: stk_ptr = 0
Race(Dhiyad901@gmail.com) 9 • stk_ptr points to the last element added to the stack 8 7 • Push – first increment the stk_ptr and then add data 6 5 4 6 • Pop – first take data out and then decrement stk_ptr 3 4 2 5 1 2 0 7 Growing UpwardsInitial state: stk_ptr = -1
Race(Dhiyad901@gmail.com) Stacks – Array Implementation class Stack { private: intmaxSize; // maximum storage capacity intstk_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 boolisFull(); // check if the stack is full boolisEmpty(); // check if the stack is empty };
Race(Dhiyad901@gmail.com) Stack::Stack(int s) { maxSize = s; stk_ptr = 0; stackArray = new int[maxSize]; } bool Stack::isEmpty() { return (stk_ptr == 0); } bool Stack::isFull() { return (stk_ptr == maxSize); } 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; }
Race(Dhiyad901@gmail.com) 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) 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) 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) 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) 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) 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) bool Queue::add(int n) { if (! isFull() ) { QueueArray[rear] = n; rear++; size++; return true; } else return false; }
Race(Dhiyad901@gmail.com) bool Queue::remove(int &n) { if (! isEmpty() { n = QueueArray[front]; front++; size--; return true; } else return false; }
Race(Dhiyad901@gmail.com) • size = 2; front = 1; rear = 3; • Initial condition • size = 0; front = 0; rear = 0; • Assume maxSize = 5 • Add 3, remove 1
Race(Dhiyad901@gmail.com) • 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) 3 2 1 MS-1 0 Circular Implementation bool Queue::add(int n) { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; }
Race(Dhiyad901@gmail.com) Circular Implementation bool Queue::remove(int &n) { if (! isEmpty() { n = QueueArray[front]; front++; if (front == maxSize) front = 0; size--; return true; } else return false; } 3 2 1 MS-1 0
Race(Dhiyad901@gmail.com) 3 2 1 MS-1 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::add(int n) { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } bool Queue::isFull() {return size == MaxSize;} bool Queue::isEmpty() {return size == 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) 3 2 1 MS-1 0 Add: rear = (rear + 1) % maxSize; Remove: front = (front + 1) % maxSize; What happens if we try to do it clockwise? 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; }
Race(Dhiyad901@gmail.com) 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) Input restricted dequeue (algorithm) remove (queue, n, f, r, side) • If (f= -1 or r= -1) then print (“queue is empty”) return (dummy value) • If (f = r) then n = queue [f] f = -1, r = -1 • If (side = ‘front) then n = queue [f] f = f + 1 • If (side = ‘rear’) then n = queue [r] r = r – 1 5. Return (n)
Race(Dhiyad901@gmail.com) 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) 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) 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) 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) Activation Records
Race(Dhiyad901@gmail.com) 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) 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) 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) How Does Recursion WorkSome 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) n = 4 n = 3 1. 2. return 1 1. 2. return 1 n = 2 1. 2. return 1 n = 1 1. 2. 3. 4. 1. 2. 3. 4. 1. 2. 3. 4. 1. 2. return 1 temp = 2 5. return 3*2 temp = 1 5. return 2*1 temp = 6 5. return 4*6 Simulation of factorial(4) • if (n<0) return 0; • else if (n <=1) return 1; • else { • temp = factorial (n-1); • return n*temp; }
Race(Dhiyad901@gmail.com) Fibonacci Sequence0,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) n = 4 n = 2 1. 2. return 1 1. 2. return 1 n = 3 1. 2. return 1 1. 2. return 1 n = 1 n = 2 1. 2. 3. 1. 2. 3. 1. 2. return 1 1. 2. return 1 1. return 1 temp1 = 2 4. temp1 = 1 4. temp2 = 1 5. return 3 temp2 = 1 5. return 2 Simulation of fibonacci(4) • if (n<=0) return 0; • else if (n<=2) return 1; else { • temp1 = fibonacci(n - 1); • temp2 = fibonacci(n - 2); • return temp1 + temp2; }
Race(Dhiyad901@gmail.com) 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) 3 Disks From Using To • How much time would it take? Estimate….. • According to the legend, that will mark the end of time!
Race(Dhiyad901@gmail.com) Tower of HonoiRecursive Solution End Condition: Recursive Step:
Race(Dhiyad901@gmail.com) 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) 3 Simulation of TOH(1, 2, 3, 3) from:1, to:2, using:3, n:3 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 2, t = 1, u = 3, n = 0 statement: 1 f = 1, t = 3, u = 2, n = 0 statement: 1 f = 3, t = 2, u = 1, n = 0 statement: 3 f = 2, t = 1, u = 3, n = 0 statement: 1 f = 1, t = 2, u = 3, n = 0 statement: 5 f = 3, t = 2, u = 1, n = 0 statement: 1 1 2 f = 2, t = 3, u = 1, n = 1 statement: 5 f = 1, t = 2, u = 3, n = 1 statement: 3 f = 1, t = 2, u = 3, n = 1 statement: 4 f = 1, t = 2, u = 3, n = 1 statement: 5 f = 2, t = 3, u = 1, n = 1 statement: 3 f = 2, t = 3, u = 1, n = 1 statement: 4 f = 3, t = 1, u = 2, n = 1 statement: 4 f = 3, t = 2, u = 1, n = 1 statement: 5 f = 3, t = 1, u = 2, n = 1 statement: 5 f = 1, t = 2, u = 3, n = 1 statement: 4 f = 1, t = 2, u = 3, n = 1 statement: 3 f = 3, t = 1, u = 2, n = 1 statement: 3 f = 3, t = 2, u = 1, n = 2 statement: 3 f = 1, t = 3, u = 2, n = 2 statement: 5 f = 1, t = 3, u = 2, n = 2 statement: 4 f = 3, t = 2, u = 1, n = 2 statement: 4 f = 3, t = 2, u = 1, n = 2 statement: 5 f = 1, t = 3, u = 2, n = 2 statement: 3 • if (n>0) • { • TOH (from, using, to, n-1); • move (to, from); • TOH (using, to, from, n-1); • } f = 1, t = 2, u = 3, n = 3 statement: 3 f = 1, t = 2, u = 3, n = 3 statement: 5 f = 1, t = 2, u = 3, n = 3 statement: 4