37
1 ADT Stack

stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

1

ADT Stack

Page 2: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

2

Stacks of Coins and Plates

Page 3: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

3

Stacks of Rocks and Books

TOP OF THE STACK TOP OF THE STACK

Add, remove rock and book from the top, or else…

Page 4: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

4

Stack at logical level • A stack is an ADT in which

elements add added and removed from only one end (i.e.,at the top of the stack).

• A stack is a LIFO “last in, first out” structure.

Page 5: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

5

Stack at Logical Level

• What operations would be appropriate for a stack?

Page 6: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

6

Stack OperationsTransformers

• Push • Pop

Observers • Top

• IsEmpty • IsFull

change state

observe state

Page 7: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

7

Stack at Application Level

• For what types of problems would be stack be useful for?

• LIFO: good for reversing data • If we push a, b, c, d into a stack, and then

pop all elements out, we get d, c, b, a • In OS/language: function call stack • Finding Palindromes • Expression evaluation and Syntax Parsing

Page 8: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

8

Function call stack• For what types of problems

would be stack be useful for? • LIFO: good for reversing data

• If we push a, b, c, d into a stack, and then pop all elements out, we get d, c, b, a

• In OS/language: function call stack

• Finding Palindromes • Expression evaluation and

Syntax Parsing

Page 9: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

9

Use stack to reverse

• Sometimes you need to output in reverse orders Convert decimal to binary: DisplayInBinary (int num) while (num>0) digit = num % 2 print digit num = num / 2

• The binary representation is printed backward • Trace it with num=21, output?

• Solution: push each digit onto a stack in the loop, after the loop, pop digits out one by one and display it.

Page 10: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

10

Use stack to backtrack

• In maze-walking algorithm, we can use stack to store all nodes that we led us to current node, so that we can backtrack when needed.

• Goal: find a path via white blocks from (0,0) to (5,5) • Need to explore: try diff. next step • and backtrack (when reach dead-end): i.e., reverse back to previous node

Page 11: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

11

Stack of ItemTypesclass StackType { public:

StackType( );

bool IsFull () const; bool IsEmpty() const; void Push( ItemType item ); void Pop(); ItemType Top() const;

};

What are the

pre and post

conditions?

Page 12: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

12

Stack Implementation

• array-based implementation: static or dynamic array

• linked-structure implementation

Page 13: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

13

class StackType { public:

StackType( );

bool IsFull () const; bool IsEmpty() const; void Push( ItemType item ); void Pop();

ItemType Top(); private:

int top; ItemType items[MAX_ITEMS]; };

2

‘c’

‘b’

‘a’

Stack items

unused slots/garbage

Page 14: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

14

Class Interface Diagram (Memory reversed to better illustrate concept)

StackType class

StackType

Pop

Push

IsFull

IsEmpty

Private data: top

[MAX_ITEMS-1] . . .

[ 2 ]

[ 1 ]

items [ 0 ]Top

Page 15: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

15

How to initialize data member top?

0 or -1

Depends on what top stores:

* initialized to 0: If it’s the next open slot * initialized to -1: if it’s the index of stack top

element

Need to be consistent in all member functions, Top(), Push(), Pop(), isfull, isEmpty()…

Below we use second option:

StackType::StackType( ) { top = -1; //index of top element in stack }

Initialize stack

Page 16: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

16

// pre: the stack has been initialized // post: return true if the stack is empty, false ow bool StackType::IsEmpty() const { return(top == -1); }

//pre: //post: bool StackType::IsFull() const { return (top = = MAX_ITEMS-1); }

Page 17: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

17

void StackType::Push(ItemType newItem) { if( IsFull() ) throw FullStack(): top++; items[top] = newItem; }

void StackType::Pop() { if( IsEmpty() ) throw EmptyStack(); top--; }

ItemType StackType::Top() { if (IsEmpty()) throw EmptyStack(); return items[top]; }

Page 18: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

18

Tracing Client Codechar letter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop( ); charStack.Push(‘K’); while (!charStack.IsEmpty( )) { letter = charStack.Top(); charStack.Pop(0)}

Private data:

top [MAX_ITEMS-1]

. .

[ 2 ]

[ 1 ]

items [ 0 ]

letter ‘V’

Page 19: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

19

Stack Implementation: linked structure• One advantage of an ADT is that the implementation

can be changed without the program using it knowing about it.

• in-object array implementation: has a fixed max. size • dynamically allocated array (as in lab2?): can be

grown when needed, but lots of copy!

• Linked structure: dynamically allocate the space for each element as it is pushed onto stack.

Page 20: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

20

ItemType is char

class StackType

StackType

Top

Pop

Push

IsFull

IsEmptyPrivate data:

topPtr

~StackType

‘C’ ‘V’

Page 21: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

21

// DYNAMICALLY LINKED IMPLEMENTATION OF STACK struct NodeType; //Forward declaration

class StackType { public: //Identical to previous implementation /* Add: copy-constructor, destructor, assignment

operator: since dynamic memory is used! */ private: NodeType* topPtr; }; . . . struct NodeType { ItemType info; NodeType* next; };

Page 22: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

22

Implementing Pushvoid StackType::Push ( ItemType newItem ) // Adds newItem to the top of the stack. { NodeType* location; location = new NodeType; location->info = newItem; location->next = topPtr; topPtr = location; }

Page 23: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

23

Deleting top element from the stack

NodeType* tempPtr;

item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr;

topPtr ‘B’ ‘X’ ‘C’ ‘L’

tempPtr

item

Page 24: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

24

Deleting top element from the stack

NodeType* tempPtr;

item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr;

topPtr

item

‘B’ ‘X’ ‘C’ ‘L’

tempPtr

‘B’

Page 25: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

25

Deleting item from the stack

NodeType* tempPtr;

item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr;

topPtr

item

‘B’ ‘X’ ‘C’ ‘L’

tempPtr

‘B’

Page 26: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

26

Deleting item from the stack

NodeType* tempPtr;

item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr;

topPtr

item

‘B’ ‘X’ ‘C’ ‘L’

tempPtr

‘B’

Page 27: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

27

Deleting item from the stack

NodeType<ItemType>* tempPtr;

item = topPtr->info; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr;

topPtr

item

‘X’ ‘C’ ‘L’

tempPtr

‘B’

Page 28: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

28

Implementing Pop

void StackType::Pop() // Remove top item from Stack. { if (IsEmpty()) throw EmptyStack(); else { NodeType* tempPtr; tempPtr = topPtr; topPtr = topPtr ->next; delete tempPtr; } }

Page 29: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

29

Implementing Top

ItemType StackType::Top() // Returns a copy of the top item in the stack. { if (IsEmpty()) throw EmptyStack(); else return topPtr->info; }

Page 30: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

30

Implementing IsFullbool StackType::IsFull() const // Returns true if there is no room for another // ItemType on the free store; false otherwise { NodeType* location; try { location = new NodeType; delete location; return false; } catch(std::bad_alloc exception) { return true; } }

Page 31: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

31

Array vs Linked Structure

• Drawback of array-based implementation: • at any point of time, array is either filled or

not • memory is either not enough, • or wasted

• Linked Structure: allocate on demand • Drawback: need to store lots of addresses

(in pointer field of node) • if ItemType is small compared to pointer,

then it’s not memory efficient

Page 32: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

32

Efficiency comparison

Page 33: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

33

C++ Standard Template Library

• a set of C++ class templates that provides common programming data structures and functions • lists, stacks, queues, hash table, many

more… • all data structures/container are implemented as

class template, which can be parameterized: • vector<int>, vector<double> … • stack<int>, stack<char> • the type in <> is type parameter, specifying

the type of items that the stack stores…

Page 34: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

34

Sample code using STL stack

Page 35: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

35

Sample code using STL stack

More info on stack

Page 36: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

36

Exercises

• use C++ STL stack to finish the code that displays a number in binary

Page 37: stack - Fordham · 2019. 10. 10. · C++ Standard Template Library • a set of C++ class templates that provides common programming data structures and functions • lists, stacks,

37

Problem Solving using Stack

• check for balanced parenthesis (, ), {, }, [, ]. • Balanced parentheses: means that each

opening symbol has a corresponding closing symbol and the pairs of parentheses are properly nested. • examples: are the following balanced? • ( ) ( ) ] • { [ ( ) ( } ) • [ () ]{ } • { [ ( )( ) ] { } }

• How to write a function/program to check?