Stack - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Stack

Description:

We can take only one plate off at a time, and only from the top of ... A Pointer Based Implementation of the ADT Sack. An Implementation that Uses the ADT List ... – PowerPoint PPT presentation

Number of Views:65
Avg rating:3.0/5.0
Slides: 49
Provided by: cisN9
Category:
Tags: sack | stack

less

Transcript and Presenter's Notes

Title: Stack


1
  • 1
  • Stack
  • The ADT Stack
  • An Array Implementation of Stack
  • A Pointer Implementation of Stack
  • Application Algebraic Expressions
  • Application Search
  • The ADT Stack
  • Metaphor A stack of (heavy) plates.
  • We can take only one plate off at a time, and
    only from the top of the stack.
  • We can put only one plate on the stack at a time.
  • LIFO Last in - First out
  • Operations for an ADT
  • Create(S) (implemented as constructor)
  • StackIsEmpty(S)
  • Push(S, newitem)
  • Pop(S)
  • GetStackTop(S)

2
  • 2
  • Create(S)
  • Creates an empty stack S.
  • StackIsEmpty(S)
  • Returns TRUE if S is empty.
  • Push(S, newitem)
  • Inserts the new item newitem on top of S.
  • Pop(S)
  • Throws away the top item from the stack.
  • GetStackTop(S)
  • Returns the top element of the stack, but it
    does not change the stack.

3
Class StackException
  • include ltexceptiongt
  • includeltstringgt
  • Using namespace std
  • class StackException public exception
  • Public
  • class StackException(const string message)
    exception(message.c_str())
  • //end StackException

4
Implementations of the ADT Stack 4
  • An Array Based Implementation of the ADT Stack
  • A Pointer Based Implementation of the ADT Sack
  • An Implementation that Uses the ADT List


Items
TOP
K
0
1
2
K
Array Indexes
MAX_STACK-1
An array based implementation
5
  • //Array-Based Implementation
  • // Header file Stack A.h for the ADT stack.
  • const int max_stack 20
  • typedef int stackItemType
  • //desired type- of stack-item is int/
  • class stackClass
  • public
  • stackClass( ) // default constructor
  • stackClass(const stackClass S)
  • // return the current value but can not alter it

6
  • 6
  • stackClass( ) // destructor corresponds to
    DestroyStack
  • boolean StackIsEmpty( ) const
  • // determine whether the stack is empty.
  • void Push (stackItemType NewItem, boolean
    Success)
  • //Adds an item to the top of a stack.
  • void Pop(boolean Success)
  • //removes the top of a stack
  • void Pop(stackItemType StackTop, boolean
    Success)
  • //retrieves and removes the top of a stack.
  • void GetStackTop(stackItemType StackTop,
    boolean Success) const
  • // retrieves the top of a stack.

7
  • 7
  • private
  • stackItemType Itemsmax_stack
  • int Top // index to the top of stack
  • // end class
  • End of header file.
  • The implementations of the functions that the
    previous header file declares are in the
    following Stack A.cpp

8
  • include StackA.h //header file
  • stackClassstackClass( ) Top(-1)
  • //end default constructor 8
  • stackClassstackClass( )
  • // end destructor
  • boolean stackClassStackIsEmpty( ) const
  • return boolean(Top lt 0)
  • // end StackIsEmpty
  • void stackClassPush(stackItemType NewIt,
    boolean Success)
  • Success boolean(Top lt max_stack -1)
  • if (Success)
  • ItemsTop NewIt
  • // end push

9
  • 9
  • void stackClassPop(boolean Success)
  • Success boolean(!StackIsEmpty( ))
  • if (Success)
  • --Top
  • //end pop
  • void stackClassGetStackTop( stackItemType
    StackTop, boolean Success) const
  • Success boolean(!StackIsEmpty( ))
  • if (Success)
  • StackTop ItemsTop
  • // end GetStackTop

10
  • //A program that uses a stack could begin as
    follows
  • include ltiostream.hgt
  • include ltStackA.hgt
  • Int main ()
  • stackItemType AnItem
  • stackClass S
  • cin gtgt AnItem // read an item
  • S.push (AnItem, Success) //push it onto stack
  • stackClassstackClass(const stackClass S)
    Top(S.Top)
  • for (int index0 index lt S.Top index)
  • Itemsindex S.Itemsindex

10
11
Header file StackP.h for ADT stack 11
  • TopPtr

10
80
16
?
6
12
  • 12
  • Pointer Implementation
  • struct stackNode
  • typedef stackNode ptrType
  • class stackClass
  • public
  • //same as for array!
  • class stackClass
  • public
  • stackClass( ) // default constructor
  • stackClass(const stackClass S) //copy
    constructor
  • // return the current value but can not alter it

13
Pointer Implementation 13
  • stackClass( ) // destructor corresponds to
    DestroyStack
  • boolean StackIsEmpty( ) const
  • // determine whether the stack is empty.
  • void Push (stackItemType NewItem, boolean
    Success)
  • //Adds an item to the top of a stack.
  • void Pop(boolean Success)
  • //removes the top of a stack
  • void Pop(stackItemType StackTop, boolean
    Success)
  • //retrieves and removes the top of a stack.
  • void GetStackTop(stackItemType StackT, boolean
    Success) const
  • // retrieves the top of a stack.

14
  • 14
  • private
  • ptrType TopPtr
  • struct stackNode
  • stackItemType Item
  • ptrType Next
  • stackClassstackClass TopPtr(NULL)
  • stackClassstackClass (const stackClass S)
  • if (S.TopPtr NULL) TopPtr NULL
  • else

15
StackP.ccp 15
  • struct stackNode
  • stackItemType Item
  • ptrType Next
  • stackClassstackClass() TopPtr(NULL)
  • stackClassstackClass (const stackClass S)
  • if (S.TopPtr NULL)
  • TopPtr NULL //original stack is empty
  • else //copy first node

16
  • 16
  • TopPtr new stackNode
  • assert (TopPtr ! NULL)
  • TopPtr-gtItem S.TopPtr-gtItem
  • // copy the rest
  • ptrType NewPrev TopPtr
  • for (ptrType Orig S.TopPtr-gtNextOrig !
    NULLOrig Orig-gtNext)
  • NewPrev-gtNext new stackNode
  • assert (NewPrev-gtNext ! NULL)
  • NewPrev NewPrev-gtNext
  • NewPrev-gtItem Orig-gtItem
  • //end for

17
  • 17
  • NewPrev-gtNext NULL
  • // end of the if
  • stackClassstackClass( )
  • boolean Success
  • //pop until stack is empty
  • pop(Success)
  • while (Success)
  • pop(Success)
  • //Assertion TopPtr NULL
  • // end destructor
  • boolean stackClassStackIsEmpty( )
  • return boolean(TopPtr NULL)
  • // end StackIsEmpty

18
  • 18
  • void stackClassPush (stackItemType NewIt,
  • boolean Success) //create new node
  • ptrType NewTopPtr new stackNode
  • Success boolean(NewTopPtr ! NULL)
  • if (Success)
  • NewTopPtr-gtItem NewItem
  • //insert the new node
  • NewTopPtr-gtNext TopPtr
  • TopPtr NewTopPtr
  • void StackClassPop(boolean Success)
  • Success boolean(!StackIsEmpty( ))
  • if (Success)
  • ptrType Temp TopPtr
  • TopPtr TopPtr -gt Next
  • delete Temp

19
  • 19
  • void stackClassGetStackTop(
  • stackItemType StackTop,
  • boolean Success)
  • Success boolean(!StackIsEmpty( ))
  • if (Success)
  • StackTop TopPtr-gtItem

20
  • 20
  • We want to write a program that recognizes
    whether an expression has balanced parentheses or
    not.
  • YES NO
  • (a b ) (c d ) (a b
  • ((a b c d)) (a b))
  • ((a b) (c d)) )a b(
  • This can be done well with a stack.
  • Idea We keep only open parentheses on the stack.
    Every time we see a closed parenthesis we pop off
    one open parenthesis. When we are at the end of
    the expression, then the stack must be empty. We
    assume that the expression is on a single line of
    input.
  • open (
  • close )

21
  • 21
  • First attempt
  • while (charptr ! \0)
  • if (charptr ( ) //charptr charptr0
  • S.Push(()
  • else if(charptr ) )
  • S.Pop
  • charptr // next character
  • This does not catch the following two mistakes
  • )ab ... should check for empty stack
  • (ab ... should check for stacks status at
    strings end

22
  • 22
  • while (charptr ! \0)
  • if (charptr ( )
  • S.Push(()
  • else if(charptr ) )
  • assert(S.StackIsEmpty( ) ! TRUE)
  • S.Pop( )
  • charptr // next character
  • assert(S.StackIsEmpty( ) TRUE)

23
  • 23
  • Recognizing Languages
  • We define a language L as follows
  • L ww w is a character string that does not
    contain a sign. w is the reverse of w.
  • PALINDROMES
  • EXAMPLES
  • AA ABBA ABAABA // in language
  • Counter Examples
  • AB ABBA ABA //not in language

24
  • 24
  • Basic Idea Keep pushing characters onto a stack
    until you see a . Then keep popping and reading,
    and compare those characters. Return FALSE if a
    popped character is different from a read
    character. Return TRUE if the stack becomes empty
    and the end of the string is found at the same
    time.
  • The following is the body of the function
  • while (charptr ! )
  • if (charptr \0) return 0
  • S.Push(charptr)
  • charptr
  • charptr // skip over
  • while (charptr ! \0)
  • if (S.StackIsEmpty( )) return 0
  • if (S.GetStackTop( ) ! charptr) return 0
  • S.Pop( )
  • charptr
  • if (S.StackIsEmpty( )) return 1 // should be!
  • else return 0

25
  • 25
  • Evaluating Postfix Expressions
  • Given is a postfix expression, compute its value.
  • 2 (3 4) (inf ix)
  • 2 3 4 (c o r r e s p o n d i n g p o
    s t f i x)
  • 2 (3 4) -gt 14
  • 2 3 4 -gt 14

26
  • 26
  • Basic Idea
  • We use a stack again, but this time we put the
    NUMBERS onto it. Every time we see a number, we
    push it. Every time we see an operator, we pop
    off two numbers, apply the operator, and push the
    result back onto the stack.
  • 2 3 4
  • 2 ... ... Push 2 on the stack
  • 3 ... ... Push 3 on the stack
  • 4 ... ... Push 4 on the stack
  • ... ... Pop off 4 Pop off 3
  • add 3 and 4 (ORDER!)
  • Push 7 on stack.
  • ... ... Pop off 7 Pop off 2
  • Multiply 2 and 7 Push
  • 14 back on the stack.

27
  • 27
  • Now the same example using the abstract data
    type.
  • S.Push(2)
  • S.Push(3)
  • S.Push(4)
  • y S.GetStackTop()
  • S.Pop()
  • x S.GetStackTop()
  • S.Pop()
  • z x y
  • S.Push(z)
  • y S.GetStackTop()
  • x S.GetStackTop()
  • z x y
  • S.Push(z)

28
  • 28
  • For the program we make a number of simplifying
    assumptions
  • No error checking
  • No unary operators
  • Only ,-,,/
  • All values are stored in variables
  • Variable names are single letters
  • stackClass S
  • char ch 2,3,4,,,\0
  • for ( ch ! \0 ch) //
    look at each char
  • if ((ch )(ch -)(ch
    )
  • (ch /)) // if char is
    operator
  • y S.GetStackTop( ) S.Pop( )
  • x S.GetStackTop( ) S.Pop( )
  • z / x ch y / S.Push(z) // use
    switch
  • else S.Push(ch)

29
  • 29
  • Note that this is a little bit far away from C.
    In the real implementation we will need a switch
    statement that distinguishes between the four
    possible operators, we cannot just write
  • x ch y
  • Also note, again, that the order of x and y is
    important.
  • Not for , but for - and /.

30
  • 30
  • Converting Infix to Postfix
  • (Complicated)
  • This uses a stack again, but this time it stores
    the operators and open
  • parentheses, as opposed to the operands.
  • The result is stored in an array PE, the
    postfix expression.
  • Algorithm
  • 1. If an operand appears in the input stream,
    then append it to the PE array.
  • 2. If a ( appears in the input stream, then
    push it onto the stack.
  • 3. If a ) appears in the input stream, then pop
    off elements from the stack and append them to
    the PE array until an open parenthesis is found
    on the stack. Pop off and discard the (. 20

31
  • 31
  • 4. If an operator appears in the input stream,
    then IF the stack is NOT EMPTY then pop off
    operators of greater or equal precedence from the
    stack and append them to PE, until
  • a) either the stack is empty
  • b) or you find an ( on the stack
  • c) or you find an operator of lower precedence
  • Then push the new operator on the stack.
  • 5. When you reach the end of the input, then pop
    off all operators from the stack and append them
    to the end of PE.

32
  • 32
  • Now we will show an example of how to actually do
    this. We convert
  • A - (B C D) / E
  • We will show the stack top on the RIGHT.
  • CH A S PE A 1.
  • CH - S - PE A 4.d)
  • CH ( S -( PE A 2.
  • CH B S -( PE AB 1.
  • CH S -( PE AB 4.b)
  • CH C S -( PE ABC 1.
  • CH S -( PE ABC 4.c)
  • CH D S -( PE ABCD 1.
  • CH ) S -( PE ABCD 3.
  • S -( PE ABCD 3.
  • S - PE ABCD 3.
  • CH / S -/ PE ABCD 4.d)
  • CH E S -/ PE ABCDE 1.
  • S - PE ABCDE/ 5.

33
  • 33
  • Why does this work?
  • This algorithm is based on the following
    observations
  • 1) Operands stay in the same order.
  • AB becomes AB and NOT BA
  • 2) Operators move only to the right, never to the
    left, relative to the operands.
  • AB ---gt AB moved to the right of B.
  • 3) Postfix expressions dont need parenthesis.
  • Code 5 pages in the book. DO TRY TO READ THEM.

34
  • 34
  • Search
  • This section uses a structure called a graph
    that will be covered in more detail much later in
    the class.
  • Given is the following problem
  • There is a map of cities, and there is a flight
    plan that describes all connections between
    cities. Then you are given two specific cities, A
    and B and asked whether you can fly from A to B.
  • Note In a real flight plan you cant be sure
    that there is a flight from B to A. We will use
    examples that make this assumption. In fact,
    there will be dead-end cities with no flights
    leaving. (Flights in, No flights out)
  • Of course this problem uses a stack, but we
    start with the representation of the map.

35
  • 35
  • Example
  • Y
    Z
  • W
    S T
  • Q X R P

36
  • 36
  • How do we represent this graph in the
    computer? There are two possibilities, but for
    now we will learn only one The Adjacency List.
  • An adjacency list is really an ARRAY OF LINKED
    LISTS. For every city there is one element in the
    array. This element is a pointer to a linked
    list. Every element of the linked list contains
    the name of ONE NEIGHBORING
  • CITY.

37
  • 37
  • Note
  • The linked list from the array position P to R
    and W does Not imply any order. It could have
    been P--gt W--gtR. It just says that there is a
    flight from P to W and there is a flight from P
    to R.
  • We need one more data structure, a boolean array
    that remembers if we already visited a city.

P Q R S T W X Y Z
NULL
R
X
X
T
W
S
R
NULL
Z
Y
Y
NULL
NULL
NULL
38
  • 38
  • Back to the problem
  • We assume that there are three files
  • Cityfile...
  • A file of cities, in alphabetical order, that
    are known to all. If there is no flight from or
    to a city, it is just not mentioned here.
  • Flightfile...
  • This is the actual flight plan. Each line
    contains a pair of cities, and such a line means
    that there is a flight from the first city to the
    second city.
  • Requestfile...
  • This looks exactly like the Flightfile, but it
    stands for a request.

39
  • 39
  • For the simplest version we want only one answer
  • you can get there from here, or
  • you cannot get there from here.
  • We use a backtrack search to find the path. If
    necessary we search exhaustively, which means
    we try every possible path. Lets call the origin
    city O, and the destination city D.
  • Either we find a path, or we conclude that no
    path exists.
  • Basic approach
  • Look at a neighbor of O. If the neighbor is
    D, then we are done. If this neighbor is not D,
    say it is C1, then we look at a neighbor of C1.
    If the neighbor of C1 is D, we are done, etc.

40
  • 40
  • Now comes the backtrack part In our
    hypothetical flight plan, there are cities where
    no flights leave at all(!) If we reach such a
    city, then we have to return to the previous
    choice and make another selection. For that I
    need to store the previous selection, and that is
    what the stack is used for.
  • Invariant The stack contains at every moment
    the cities on a trip from O to the current city.
    O is at the bottom of the stack. By popping off
    the top element, I can return to the previous
    city.
  • After I popped a city off the stack, how do I
    make sure that I dont go there again? Thats
    where the visited array is used.

41
  • 41
  • Important notes
  • The described search algorithm does not define at
    all in what order we are visiting cities. In
    practice we use the order in the adjacency list.
  • 2. The resultant path might be a very bad one.
    There might exist a direct flight, and I might
    choose a much longer path instead.
  • 3. The result will, however, never contain a
    circle. The visited array protects me from
    that.
  • Now comes the basic algorithm.

42
  • 42
  • search(O,D)
  • S.Push(O) visitedO TRUE
  • while ((!S.StackIsEmpty( ))
  • (S.GetStackTop( ) ! D)
  • C1 S.GetStackTop( )
  • if (/there are no flights from C1 to any
    unvisited city/) S.Pop( )
  • else
  • // select any unvisited neighbor C of C1
  • S.Push(C) visitedC TRUE
  • Example In the previous map, how do we get from
    P to Z?
  • We start with a stack containing P. As before,
    the top is at the right.
  • S

P
43
  • 43
  • Example
  • Y
    Z
  • W
    S T
  • Q X R P

S PR S PRX S PR S P S PW S
PWS S PW S PWY S PWZ
44
  • 44
  • The relationship between stacks and recursion
  • We could have solved the same search problem in
    a recursive manner. In fact, this is always true.
    A recursive program can be modeled by a program
    using a stack. There is a deeper reason for this
    The INTERNAL
  • IMPLEMENTATION of recursion in C uses a stack.

45
  • 45
  • RecursiveSearch(O,D)
  • visitedO TRUE
  • if (O D)
  • // report success
  • else
  • for ( C all neighbors of O )
  • RecursiveSearch(C,D)
  • Note that this is very rough. The FOR loop would
    go on after we already were successful.

46
  • 46

47
  • 47

48
  • 48
Write a Comment
User Comments (0)
About PowerShow.com