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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Introduction to Stacks & Queues.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
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.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
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.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
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.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R1. Elementary Data Structures.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
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.
Stacks  Introduction  Applications  Implementations  Complex Applications.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
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)
CHP-3 STACKS.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
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.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
CSCE 210 Data Structures and Algorithms
Data Structures Using C++ 2E
CSCE 210 Data Structures and Algorithms
CS505 Data Structures and Algorithms
Stacks Stacks.
MEMORY REPRESENTATION OF STACKS
Homework 4 questions???.
Cinda Heeren / Geoffrey Tien
Stacks.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Algorithms and Data Structures
STACK CHAPTER 03 Developed By :- Misha Ann Alexander Data Structures.
Visit for more Learning Resources
Stack.
Stacks and Queues 1.
Jordi Cortadella and Jordi Petit Department of Computer Science
Stack.
5.3 Implementing a Stack Chapter 5 – The Stack.
Presentation transcript:

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 Some Applications of Stacks

3 1. Introduction to the Stack Data Structure  A simple data container consisting of a linear list of elements  Access is by position (order of insertion)  All insertions and deletions are done at one end, called top  Last In First Out (LIFO) structure  Two basic operations: push: add to top pop: remove from top

4 1. Introduction to the Stack Data Structure  A simple data container consisting of a linear list of elements  Access is by position (order of insertion)  All insertions and deletions are done at one end, called top  Last In First Out (LIFO) structure  Two basic operations: push: add to top pop: remove from top

5 Example

6 Example top ++toptop push pop top top--

7 Run-time stack used in function calls Page-visited history in a Web browser Undo sequence in a text editor Removal of recursion Conversion of Infix to Postfix notation Evaluation of Postfix expressions Reversal of sequences Checking for balanced symbols Some Stack Applications

8 Stack Class Operations construct: construct an empty stack stackIsEmpty  bool : return True if stack is empty stackIsFull  bool : return True if stack is full push(el) : add element (el) at the top pop(el): retrieve and remove the top element stackTop(el): retrieve top element without removing it

9 The stack may be implemented as a dynamic array. The capacity (MaxSize) will be input as a parameter to the constructor (default is 128) The stack ADT will be implemented as a template class to allow for different element types. 2. Array Based Stack Class Definition

10 // File: Stackt.h // Stack template class definition. // Dynamic array implementation #ifndef STACKT_H #define STACKT_H template class Stackt { public: Stackt (int nelements = 128);// Constructor ~Stackt ();// Destructor A Stack Class Definition

11 // Member Functions void push(Type & );// Push Type pop(); // Pop Type stackTop() const; // retrieve top value bool stackIsEmpty() const;// Test for Empty stack bool stackIsFull() const;// Test for Full stack private: Type *stack;// pointer to dynamic array int top, MaxSize; }; #endif // STACKT_H #include "Stackt.cpp" A Stack Class Definition

12 Stackt (int s) //constructor { MaxSize = s; stack = new Type [MaxSize]; top = -1; } public void push(Type & i) { top++; stack[top] = I;} // increment top, insert item Type pop() {Type result = stack [top]; top--; return result; } Type stackTop() const {Type result = stack [top]; return result; // not removed} A Stack Class Definition

13 bool stackIsEmpty() const { retrun (top == -1); } bool stackIsFull() const; {retrun (top == MaxSize – 1) ;} ~Stackt () {delete[] stack ;} A Stack Class Definition

14 A stack can be implemented as a linked structure. Requires more space than array implementations, but more flexible in size. Easy to implement because operations are at the top (in this case the head node) 3. Linked Stacks

15 Node Specification // The linked structure for a node can be // specified as a Class in the private part of // the main stack class. class node// Hidden from user { public: Type e;// stack element node *next;// pointer to next node }; // end of class node declaration typedef node * NodePointer; NodePointer top;// pointer to top

16 Push Operation top First pnew Last New 2 3 push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 1

17 Push Operation top First Last 2 3 push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; pnew New 1

18 Pop Operation 2 3 cursor top pop(v): v = top->e; cursor = top; top = top->next; delete cursor; 1

19 // File: StackL.h // Linked List Stack class definition #ifndef STACKL_H #define STACKL_H template class StackL { public: StackL();// Constructor ~StackL();// Destructor void push(Type );// Push void pop();// Pop Linked Stack Class

20 void stackTop() const;// retrieve top bool stackIsEmpty() const;// Test for Empty stack private: // Node Class class node { public: Type e;// stack element node *next; // pointer to next node node() : e(value), next(link){} }; // end of class node declaration Linked Stack Class

21 typedef node * NodePointer; NodePointer top;// pointer to top }; #endif // STACKL_H Linked Stack Class

22 // STACKL.cpp #include “StackL.h” // constructor StackL : : StackL {top=0;} // Destructor StackL : :- StackL { StackL : :NodePointer currPtr = top, nextPtr; while (currPtr != 0) { nextPtr = currPtr->next; delete currPtr; currPtr = nextPtr; } Linked Stack Class

23 // STACKL.cpp #include “StackL.h” // empty() bool StackL : :stackIsEmpty() const {return (top == 0)}; // push() void StackL : :push(Type &value) { top = new StackL : :node(value, top); }/* The push operation is simple insertion at the beginning of a linked list. We get a new node containing the item to be added to the stack and have it point to the top node in the stack. The node constructor sets the data part of the new node equal to value and the next part equal to top pointer.*/ Linked Stack Class

24 // STACKL.cpp #include “StackL.h” // top() Type StackL : : stackTop() const { if (! stackIsEmpty()) return (top->data); else cout<<“Empty”;} //pop() void StackL : :pop() { if (! stackIsEmpty()) Stack::NodePointer ptr= Top; Top = Top->next; delete ptr; else cout<<“Empty”;} Linked Stack Class

25 Run-time stack used in function calls. Conversion from Decimal to Hexadecimal Balancing Enclosure Symbols. Evaluation of Postfix Expressions. Converting Infix Expressions to Postfix. 4. Some Applications of Stacks

26 (a) Run-time stack used in function calls

27 (a) Run-time stack used in function calls

28 (a) Run-time stack used in function calls

29 (a) Run-time stack used in function calls

30 (a) Run-time stack used in function calls

31 // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt s; string H = “”; do {char c; rem = n % 16;n = n / 16; if (rem < 10) c = char (('0') + rem); else c = char (int('A') + rem - 10); s.push(c); }while ( n != 0); while (!s.stackIsEmpty()) {s.pop(c); H = H + c;} return H; } (b) Decimal to Hexadecimal Conversion

32 Given a text file containing a sequence of characters, we want to check for balancing of the symbols ( ), [ ], { }. Algorithm: bool EnclosureBalance (filename) { Open file filename; Initialize an empty stack of characters; balanced = true; for each character (ch) read until end of file : { If (ch is a left symbol) push ch on the stack; (c) Balancing Enclosure Symbols

33 else if (ch is a right symbol) then if (stack is empty) balanced = false; else { pop the stack; if (popped symbol is not the corresponding left symbol) balanced = false; } At the end of the file, if (stack is not empty) balanced = false; return balanced; } (c)Balancing Enclosure Symbols

34 (c)Balancing Enclosure Symbols

35 (c)Balancing Enclosure Symbols

36 Regular expressions are written in “infix” notation, i.e., operator between two operands, e.g., (A+B) * (C- (D+E)) Parentheses are used to force precedence Reverse Polish Notation (RPN) or “postfix”)(many compilers first transform these infix expressions into prefix) does without parentheses. e.g. the above expression is: A B + C D E + - * Postfix expressions like A B + are evaluated as A + B (c) Evaluation of Postfix Expressions

37 (c) Evaluation of Postfix Expressions

38 The idea is: The compiler scans from left to right until an operator (+,-,*,/) is encountered. Apply operator between the previous operands. Replace the two previous operands by the result. This suggests to use a stack to store operands and the results. Evaluation of Postfix Expressions

39 Evaluation of Postfix Expressions (Example) A B + C D E + - * R1 C D E + - * R1 C R2 - * R1 R3 * R1 R3 * = RESULT

40 (2+3) * (2- (4+1)) → * Evaluation of Postfix Expressions (Example) * * * 5 -3 * 5 -3 * = RESULT = -15

41 Initialize a stack (S) of characters For each character from left to right Get next character If operand, push it on S If an operator: –Pop two values (error if there are no two values) –Apply operator –Push result back onto (S) At the end, result is on top of (S) (the only value, otherwise an error) Evaluation of Postfix Expressions (Algorithm)

42 Initialize an operator stack, s While not end of infix expression do the following: read next symbol in case the symbol is: an operand:write the operand ‘ ( ‘ :push onto s ‘ ) ’ :pop and write all operators until encountering ‘ ( ‘, then pop ‘ ( ‘ ‘ * ’ or ‘ / ’ :1-pop and write all ‘ * ’ and ‘ / ’ operators from the top down to but not including the top most ‘ ( ‘, ’ + ’, ’ - ’ or to the bottom of the stack 2-push the ‘ * ’ or ‘ / ’ ‘ + ’ or ‘ - ’ :1-pop and write all operators from the top down to but not including the topmost ‘ ( ‘ or to the bottom of the stack 2-push the ‘ + ’ or ‘ - ’ End of exp:pop and write all operators (e) Conversion from Infix to Postfix Expressions

43 Example : convert the 7*8-(2+3) from infix to postfix (e) Conversion from Infix to Postfix Expressions

44 Example : convert the 7*8-(2+3) from infix to postfix (e) Conversion from Infix to Postfix Expressions

45 Example : convert the 7*8-(2+3) from infix to postfix Assignment: write a c++ program to convert from infix to postifx (e) Conversion from Infix to Postfix Expressions