abstract data types stacks - city university of new...

34
CSC 211 Intermediate Programming CSC 211 Intermediate Programming CSC 211 Intermediate Programming CSC 211 Intermediate Programming Abstract Data Types Abstract Data Types Stacks Stacks Stacks Stacks 1

Upload: others

Post on 21-May-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

CSC 211 Intermediate ProgrammingCSC 211 Intermediate ProgrammingCSC 211 Intermediate ProgrammingCSC 211 Intermediate Programming

Abstract Data TypesAbstract Data TypesStacksStacksStacksStacks

1

Page 2: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Abstract Data Type (ADT)Abstract data types (ADT) – declaration of data; declaration ofoperations. Users of ADT are not concerned how a task is done,but what the ADT can do.but what the AD can do.

ADT includes set of definitions allowing the programmers to usethe functions while hiding the implementation.

2

Page 3: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Abstract Data Type

3

Page 4: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

StacksStacksStacksStacks

4

Page 5: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Stacks

5

Page 6: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

top F

D

EtopD

E

C

B

C

B

6bottom Abottom A

Page 7: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Abstract Data Type (ADT)

A stack is a sequence of elements in which the only element that can be removed or accessed/modified is th l t th t t tl i t dthe element that was most recently inserted.

Objects can be inserted at any time, but only the last (the most-recently inserted) object can be removedremoved.

Inserting an item is known as “pushing” onto the stack. “Popping” off the stack is synonymous pp g y ywith removing an item.

A PEZ® dispenser as an analogy:

7

Page 8: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

• A stack is an abstract data type (ADT) that supports two main methods:– push(o): Inserts object o onto top of stack– pop(): Removes the top object of stack and returns it; if the

k istack is empty, an error occurs

• The following support methods should also be defined:– size(): Returns the number of objects in stack– size(): Returns the number of objects in stack– isEmpty(): Return a boolean indicating if stack is empty.– top(): Return the top object of the stack, without

8

p() p j ,removing it; if the stack is empty, an error occurs.

Page 9: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

9

Page 10: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

10

Page 11: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

11

Page 12: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

12

Page 13: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

13

Page 14: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Definition of a stack as an ADT (abstract data type):

A stack is an ordered collection of data items in which access is possible

only at one end, called the top of the stack.

So, we can begin the declaration of our class by selecting data members:

Provide an array data member to hold the stack elements.

Provide a constant data member to refer to the capacity of the array.

Provide an integer data member to indicate the top of the stack.g p

14

Page 15: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Problems:

We need an array declaration of the form

ArrayElementType myArray[ARRAYCAPACITY];— What type should be used?

Solution (for now): Use the typedef mechanism:

typedef int StackElement;typedef int StackElement;// put this before the class declaration. StackElement is now a

synonym for int.Wh t b t th it ?— What about the capacity?

const int STACK_CAPACITY = 128;// put this before the class declaration so it is easy to change // p y g

when necessary

— Then declare the array as a data member in the private section:

StackElement myArray[STACK CAPACITY];

15

StackElement myArray[STACK_CAPACITY];

Page 16: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Notes:

The typedef makes StackElement a synonym for int. Putting it outside

the class makes it accessible throughout the class and in any file that

#includes Stack.h. If in the future we want a stack of reals, or

characters, or . . ., we need only change the typedef:

typedef double StackElementType;

or

typedef char StackElementType;

or . . .

When the class library is recompiled, the type of the array's elements

will be double or char or . . .

16

Page 17: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Example 1: Class Stack

/* Stack.h provides a Stack class.** Basic operations:* Basic operations:* Constructor: Constructs an empty stack* empty: Checks if a stack is empty* push: Modifies a stack by adding a value at the top* top: Accesses the top stack value; leaves stack unchanged* pop: Modifies a stack by removing the value at the top pop: Modifies a stack by removing the value at the top* display: Displays all the stack elements* Class Invariant:* 1 The stack elements (if any) are stored in positions* 1. The stack elements (if any) are stored in positions* 0, 1, . . ., myTop of myArray.* 2. -1 <= myTop <= STACK_CAPACITY

17

------------------------------------------------------------------*/

Page 18: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

#include <iostream>#include <iostream>using namespace std;#ifndef STACK#define STACK#define STACKconst int STACK_CAPACITY = 128;typedef int StackElement;class Stackclass Stack{/***** Function Members *****/public:public:/* --- Constructor ---** P diti A t k h b d l d* Precondition: A stack has been declared.* Postcondition: The stack has been constructed as an * empty stack.**********************************************/

18

**********************************************/Stack();

Page 19: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

/* --- Is the Stack empty? ---* Receive: Stack containing this function (implicitly)* Returns: True iff the Stack containing this function is empty Returns: True iff the Stack containing this function is empty**************************************************/bool Empty() const;/* --- Add a value to the stack ---** Receive: The Stack containing this function (implicitly)* A value to be added to a Stack* Return: The Stack (implicitly), with value added at its * top, provided there's space* Output: "Stack full" message if no space for value*********************************************/*********************************************/void Push(StackElement value);/* --- Display values stored in the stack ---** Receive: The Stack containing this function (implicitly)* The ostream out* Output: The Stack's contents, from top down, to out

19

Output: The Stack s contents, from top down, to out***************************************/void display(ostream & out) const;

Page 20: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

/* --- Return value at top of the stack ---

*

* Receive: The Stack containing this function (implicitly)

* Return: The value at the top of the Stack, if nonempty;

* l " b l "* else a "garbage value"

* Output: "Stack empty" message if stack is empty

****************************************//

StackElement Top() const;/* --- Remove value at top of the stack ---

**

* Receive: The Stack containing this function (implicitly)

* Return: The Stack containing this function with its topg p

* value (if any) removed

* Output: "Stack-empty" message if stack is empty.

20

*****************************************/

void Pop();

Page 21: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

/***** Data Members *****/

private:p a

StackElement myArray[STACK_CAPACITY];

int myTop;int myTop;

}; // end of class declaration

#endif#endif

21

Page 22: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Example 1: Implementation of Class Stack

/* Stack.cpp -- implementation file for Stack.h */#include "Stack.h"#include <iostream>#include <iostream>using namespace std;

//--- Definition of Class Constructor

Stack::Stack()

{{

myTop = -1;

} }

//--- Definition of empty

bool Stack::Empty() const

22

{ return (myTop == -1); }

Page 23: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Example 1: Implementation of Class Stack cont’d

//--- Definition of push()void Stack::Push(StackElement value){if (myTop < STACK_CAPACITY - 1) {++myTop;myArray[myTop] = value;

}}elsecerr << "*** Stack is full -- can't add new value ***\n"cerr << Stack is full can t add new value \n

<< "Must Increase value of STACK_CAPACITY in Stack.h\n";

23

}

Page 24: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

//--- Definition of display()void Stack::display(ostream & out) const{for (int i = myTop; i >= 0; i--)for (int i = myTop; i >= 0; i--) out << myArray[i] << endl;

}//--- Definition of top()StackElement Stack::Top() const{{if (myTop >= 0)return (myArray[myTop]);( y y[ y p]);

cerr << "*** Stack is empty -- can't display a value ' ***\n";

}

24

}

Page 25: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

//--- Definition of pop()void Stack::Pop(){if (myTop >= 0) // Preserve stack invariantmyTop--;

elsecerr << "*** Stack is empty can't remove a valuecerr << *** Stack is empty -- can t remove a value ***\n";

}}

25

Page 26: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Driver Program

/* Stack tester 1

****************************************/

#include "Stack.h" // our own -- <stack> for STL version

#include <iostream>

i tdusing namespace std;

int main()

{{

Stack s;

cout << "s empty? " << s.Empty() << endl;

for (int i = 1; i <= 128; i++) s.Push(i);

cout << "Stack should now be full\n";

26

s.Push(129);

}

Page 27: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

/* Stack tester 2*****************************************/#i l d "St k h" // t k f STL i#include "Stack.h" // our own -- <stack> for STL version#include <iostream>using namespace std;int main()int main(){

Stack s;cout << "s empty? " << s Empty() << endl;cout << s empty? << s.Empty() << endl;

for (int i = 1; i <= 4; i++) s.Push(2*i);cout << "Stack contents:\n";s.display(cout);p y( );cout << "s empty? " << s.Empty() << endl;cout << "Top value: " << s.Top() << endl;while (!s.Empty())

{cout << "Popping " << s.Top() << endl;

s.Pop();}

27

}cout << "s empty? " << s.Empty() << endl;

}

Page 28: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Example 2: Class Stack // Stack2.h

// ItemType : the class definition of the objects on the stack.// MAX_ITEMS: the maximum number of items on the stack.const int MAX ITEMS = 5;const int MAX_ITEMS = 5;typedef int ItemType;class StackType{{public:

StackType();// Class constructor// Class constructor.void MakeEmpty();// Function: Sets stack to an empty state.// Post: Stack is empty// Post: Stack is empty.bool IsFull() const;// Function: Determines whether the stack is full.// P St k h b i iti li d

28

// Pre: Stack has been initialized.// Post: Function value = (stack is full)

Page 29: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

bool IsEmpty() const;// Function: Determines whether the stack is empty.// Pre: Stack has been initialized.// Post: Function value = (stack is empty)void Push(ItemType item);void Push(ItemType item);// Function: Adds newItem to the top of the stack.// Pre: Stack has been initialized and is not full.// P t It i t th t f th t k// Post: newItem is at the top of the stack.void Pop(ItemType& item);// Function: Removes top item from the stack and returns it in item.// Pre: Stack has been initialized and is not empty.// Post: Top element has been removed from stack.// item is a cop of the removed item.// item is a cop of the removed item.

private:int top;ItemT pe items[MAX ITEMS] // items is a pointe to an item

29

ItemType items[MAX_ITEMS]; // items is a pointer to an item};

Page 30: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Definitions of Stack Operations

MakeEmpty and the class constructor should set top to –1.

IsEmpty should compare top to –1.

IsF ll sho ld compa e top ith MAX ITEM 1IsFull should compare top with MAX_ITEM – 1.

30

Page 31: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Example 2: Implementation of Class Stack

// The function definitions for the non-templated, non-dynamic storage-// allocation version of class StackType.#include "Stack2 h"#include Stack2.hStackType::StackType(){

top = -1;top = -1;}void StackType::MakeEmpty(){{

top = -1;}bool StackType::IsEmpty() constbool StackType::IsEmpty() const{

return (top == -1);}

31

}

Page 32: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

bool StackType::IsFull() const{

return (top == MAX ITEMS-1);return (top == MAX_ITEMS 1);}void StackType::Push(ItemType newItem) {{

top++;items[top] = newItem;

}}void StackType::Pop(ItemType& item){

item items[top];item = items[top];top--;

}

32

Page 33: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Before we call Push , we must make sure that the stack is not full.if (!stack.IsFull( ) )

stack.Push(item) ;If the stack is full when we invoke Push, the resulting condition is stack overflow. Error checking for overflow conditions may be handled in a

b f diff tnumber of different ways.We could check for overflow inside Push (instead of making the calling program do the test). We would need to tell the caller whether or not the Push was possible which we could do by adding a bool variable overFlowPush was possible, which we could do by adding a bool variable overFlowto the parameter list. Here is the revised algorithm.Push (Checks for Overflow)

IF stack is fullIF stack is fullSet overFlow to true

ELSESet overFlow to falseSet overFlow to falseIncrement topSet items[top] to newItem

Which version of Push to use in a program depends on the specifications

33

Which version of Push to use in a program depends on the specifications. Our Stack ADT specification uses the first version because the preconditionfor Push states that the stack is not full.

Page 34: Abstract Data Types Stacks - City University of New Yorknatacha/TeachFall_2010/CSC211/Notes_CPP/… · Abstract Data Type (ADT) Abstract data types (ADT) – declaration of data;

Stack Overflow The condition resulting from trying to push an

element onto a full stack.

T i k P i l t d h th ll t fi t t t fTo invoke Pop as implemented here, the caller must first test for an

empty stack:

if (!stack.IsEmpty ( ) )if (!stack.IsEmpty ( ) )

stack.Pop(item) ;

If the stack is empty when we try to pop it, the resulting condition is p y y p p , g

called stack underflow. Just as we can test for overflow within the

Push operation, we could test for underflow inside the Pop function.

Th l ith f P ld h t b difi d li htl t tThe algorithm for Pop would have to be modified slightly to return a

bool value underFlow in addition to the popped item.

Stack Underflow The condition resulting from trying to pop an

34

Stack Underflow The condition resulting from trying to pop an

empty stack.