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.

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Stacks, Queues, and Linked Lists
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
Stacks  a data structure which stores data in a Last-in First-out manner (LIFO)  has a pointer called TOP  can be implemented by either Array or Linked.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
 Balancing Symbols 3. Applications
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Infix, Postfix, Prefix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
CS 206 Introduction to Computer Science II 10 / 15 / 2008 Instructor: Michael Eckmann.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Implementing and Using Stacks
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Objectives of these slides:
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
Chapter 4 Stacks
Queues.
Homework 4 questions???.
Objectives In this lesson, you will learn to: Define stacks
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Data Structures – Week #3
Algorithms and Data Structures
PART II STACK APPLICATIONS
Stacks Chapter 5 Adapted from Pearson Education, Inc.
UNIT-I Topics to be covere d 1.Introduction to data structures.
The List, Stack, and Queue ADTs
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues 1.
Stacks and Queues CSE 373 Data Structures.
Stack.
Data Structures – Week #3
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
LINEAR DATA STRUCTURES
Presentation transcript:

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)‏

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.

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.

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

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

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

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

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 };

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); }

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.

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

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.

Uses of Queue Many real life applications ( banks, bill paying in shopping malls, etc ) Process Scheduling Memory Management Trees traversing etc

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 };

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 }

bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; size++; return true; } else return false; }

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

Assume maxSize = 5 Initial condition size = 0; front = 0; rear = 0; Add 3, remove 1 size = 2; front = 1; rear = 3;

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)‏

Circular Implementation bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } MS-1

Circular Implementation bool Queue::remove(int &n)‏ { if (! isEmpty() { n = QueueArray[front]; front++; if (front == maxSize) front = 0; size--; return true; } else return false; } MS-1

bool Queue::add(int n)‏ { if (! isFull() ) { QueueArray[rear] = n; rear++; if (rear == maxSize) rear = 0; size++; return true; } else return false; } 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; }

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; } MS-1 Add:rear = (rear + 1) % maxSize; Remove:front = (front + 1) % maxSize; What happens if we try to do it clockwise?

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

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 If (side = ‘rear’) then n = queue [r] r = r – 1 5. Return (n)

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

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

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.

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

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

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.

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

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.

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

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

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

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

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.

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.

Activation Records

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.

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; }

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 }

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; }

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

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)‏ }

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 = return 1 n = n = temp1 = return 1 n = return 1 temp2 = 1 5. return return 1 temp1 = return 1 n = return 1 temp2 = 1 5. return return 1

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.

FromUsingTo 3 Disks How much time would it take? Estimate….. According to the legend, that will mark the end of time!

Tower of Honoi Recursive Solution End Condition: Recursive Step:

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 } }

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