Sunteți pe pagina 1din 33

Stacks

Lecture 3

By: Hani

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 1
Education, Inc. All rights reserved. 0-13-140909-3
Introduction to Stacks
A stack is a last-in-first-out (LIFO) data structure
Adding an item
Referred to as pushing it onto the stack
Removing an item
Referred to as popping it from the stack

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 2
Education, Inc. All rights reserved. 0-13-140909-3
Stacks
In a stack the three natural operations are
Insert, Delete and Find. These are renamed
as
Push (insert At Front),
Pop (remove From Front) and
Top (peak).
We can combine Pop and Top operations
and return the popped item in Top. We also
need an operation to create the stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 3
Education, Inc. All rights reserved. 0-13-140909-3
Stack Functions
1- If a plate is added to the stack, those below it are
pushed down and cannot be accessed.
2- If a plate is removed from the stack, those below
it pop up one position.
3- The stack becomes empty when there are no
plate in it.
4- The stack is full if there is no room in it for more
plates.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 4
Education, Inc. All rights reserved. 0-13-140909-3
A Stack
Definition:
An ordered collection of data items
Can be accessed at only one end (the top)
Operations:
construct a stack (usually empty)
check if it is empty
Push: add an element to the top
Top: retrieve the top element
Pop: remove the top element

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 5
Education, Inc. All rights reserved. 0-13-140909-3
Procedure of PUSH and POP
Procedure PUSH(item, stack, n, top)
//Insert item into the stack of maximum size n; top is the number
of elements currently in stack//
if top>= n then report STACK_FULL
else top = top +1;
stack(top) = item
end PUSH

Procedure POP(item, stack, top)


//removes the top element of stack and stores it in item unless stack is
empty //
if top<0 then report STACK_EMPTY
else item = stack(top)
top = top -1
end POP

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 6
Education, Inc. All rights reserved. 0-13-140909-3
Designing A Stack Class
Designing a class consist of identifying those operations that are needed
to manipulate the real-world object being modeled by the class.

In our definition of stack, we identified 5 basic operations:


Construct, Empty, Push, Top and Pop.

Our class must, therefore have (at least) the following operations:

1. Construction: Initialize an empty stack. (It will first have to create the
stack.)
2. Empty Operation: Examines a stack and produces false or true
depending on whether the stack contains any values.
3. Push Operation: Modifies a stack by adding a value at the top of the
stack.
4. Top Operation: Retrieves the value at the top of the stack.
5. Pop Operation: Modifies a stack by removing the value at the top of
the stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 7
Education, Inc. All rights reserved. 0-13-140909-3
Implementing A Stack Class
Once a class has been designed, it must be implemented,
which involves two steps:
1- Defining data members to represent the objects being
modeled.
2- Defining the operations identified in the design phase.

For a container class such as stack, the data


members provide the storage structure for the stack
elements together with any other items that will prove
useful or necessary in implementing the operations.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 8
Education, Inc. All rights reserved. 0-13-140909-3
Selecting Data Members
A stack must store a collection of values, So
we begin by considering what kind of storage
structure to use.
Stack is a sequence of data items, so we
should use an array to store these items.
With each stack element occupying one
position in the array.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 9
Education, Inc. All rights reserved. 0-13-140909-3
First Attempt
Example:
Suppose we have a stack with an array of capacity 8 and that the
stack contains 6 integers 77, 121, 64, 234, 51, and 29 with the 77 at
the top and the other integers in the given order below it.

[0] 77
[1] 121
[2] 64
[3] 234
[4] 51
[5] 29
[6] ?
[7] ?
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 10
Education, Inc. All rights reserved. 0-13-140909-3
Selecting Storage Structure
Let position 0 be top of stack
Consider, however, what happened if we now perform the three operations push 95,
push 80, and pop in this order:
Requires much shifting
Each time a new value is pushed onto the stack, all the items in the
stack must be moved down one slot in the array to make room for it at
The top.
Each time a value is removed from the stack, all of the items in the
Array must be moved up so that the top value is in location 0.
The top.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 11
Education, Inc. All rights reserved. 0-13-140909-3
A Better Approach
A better approach is to let position 0 be the bottom of the
stack and let the stack grow toward the end of the array.

Using a variable myTop to keep track of the top of the stack, and then
push and pop at this location.

No shifting of array elements is necessary. So we can begin building our


stack class by selecting data members.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 12
Education, Inc. All rights reserved. 0-13-140909-3
What do we need ?
1- An array to hold the stack element.
2- An integer to indicate the top of the stack.
However, an array declaration has the form

Syntax ArrayElementType array [CAPACITY];

For ArrayElementType, we will use a typedef declaration of the form.

Syntax Typedef ArrayElementType stackElement;

13
Typedef

typedef int StackElement;


Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
Makes StackElement a synonym for int.

In future if we want a stack of double we need only change the typedef


Declaration to:

typedef double StackElement;

For a stack characters, we need only change it to:

typedef char StackElement;

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 14
Education, Inc. All rights reserved. 0-13-140909-3
Typedef
When the class library is recompiled, the
type of the arrays elements will be double or
char.
We will put this typedef declaration ahead of
the class declaration, so it is easy to change
when we need a new stack element type.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 15
Education, Inc. All rights reserved. 0-13-140909-3
Class Declaration for a Stack Data Type

#include <iostream>
using namespace std;

const int STACK_CAPACITY = 128;


typedef int StackElement;

class Stack
{
public:
/***** Function Members *****/

private:
/***** Data Members *****/
StackElement myArray[STACK_CAPACITY];
int myTop;
};

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 16
Education, Inc. All rights reserved. 0-13-140909-3
Implementing Operations
Constructor
Compiler will handle allocation of memory
Empty
Check if value of myTop == -1
Push (if myArray not full)
Increment myTop by 1
Store value in myArray [myTop]
Top
If stack not empty, return myArray[myTop]
Pop
If array not empty, decrement myTop
Output routine added for testing

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 17
Education, Inc. All rights reserved. 0-13-140909-3
Constructors
The compiler will allocate memory for the data members myArray and
myTop, so the stack constructors need only do the initialization
necessary to create an empty stack.
Because myTop always points at the array element containing the top
element, it seems natural to assign myTop the value -1 to signal an
empty stack:
myArray [STACK_CAPACITY -1] ?
.
.
.
myArray[3] ?
myArray[2] ?
myArray[1] ?
myArray[0] ?
myTop = -1 18
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
A Constructor for the Stack
Class
In Stack.h
Class Stack
Given this function, a declaration
{
Stack s;
/***** Function Members *****/
Public:
Will construct s as follows:
/ Constructors / s
Stack();
/***** data Members *****/ 0 1 2 3 4 127
Private:
stackElement myArray [STACK_CAPACITY]; myArray ? ? ? ? ? . . . ?
Int myTop;
}; // End of class declaration myTop -1

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 19
Education, Inc. All rights reserved. 0-13-140909-3
Empty Stack
The operation to check if a stack is empty or not.
It will check the myTop data member to see whether it is -1.

In Stack.h Test Driver


Class Stack
{ #include stack.h
/***** Function Members *****/
#include <iostream>
Public:
using namespace std;
bool empty () const;
/***** data Members *****/
Private: Int main ()
stackElement myArray [STACK_CAPACITY]; {
Int myTop; stack s;
}; // End of class declaration cout << s empty? << s.empty() <<
endl;

S empty? true
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 20
Education, Inc. All rights reserved. 0-13-140909-3
Push
A specification for the push operation is
1. Receive: a stack object and a value to add to the
stack
2. Return: the modified stack with value added at its
top, provided there is room.
Because push modifies the stack object, it cannot
be a constant function because it must modify the
data members.

Void push (const StackElement & value );

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 21
Education, Inc. All rights reserved. 0-13-140909-3
Algorithm for Push
1. check if the array is full by checking if
myTop is equal to the array limit.
2. if it is not then
A. Increment myTop by 1.
B. Store the item in myArray [myTop].

Otherwise
An error (stack full) has occurred.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 22
Education, Inc. All rights reserved. 0-13-140909-3
Push Operation for the Stack Class
In Stack.h Stack.cpp
Class Stack Void Stack:: push (const StackElement & value)
{ {
/***** Function Members *****/ if (myTop < STACK_CAPACITY -1)
Public: {
Void push (const StackElement & Value); ++myTop;
/***** data Members *****/ myArray [myTop] = value;
Private: }
... Else
}; // End of class declaration cerr << ** Stack is full -- cannot add any value **;
// Definition of Class Constructor << Must increase value of
STACK_CAPACITY in Stack.h;

Add to test Driver


For (int I = 1; I<=128; i++) S empty? True
s.Push (i); Stack should now be full
Out put ** Stack is full cannot add new value **
Cout<< Stack sould now be full; Must increase value of STACK_CAPACITY in
s.push(129); Stack.h

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 23
Education, Inc. All rights reserved. 0-13-140909-3
Output Operation
Is not one of the basic, but its necessary.
Use display ( ) function to show the values store in array (myArray
[myTop] ).

In Stack.h In stack.cpp
Class Stack Void stack:: display (ostream & out) const;
{ {
/***** Function Members *****/ for (int i= myTop; i >=0; i++)
Public: out<<myArray [i] << endl;
Void display (ostream & out) const; }
/***** data Members *****/
Private: Modify Test Driver
... For (int i=1; i<=4; i++) S empty? True
}; // End of class declaration s.push(2 * i); Stack contents:
// Definition of Class Constructor Cout<< Stack contents: \n; 8
s.display(cout); 6
Cout<< s empty? << s.empty () << endl; 4
2
S empty? false
Output
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 24
Education, Inc. All rights reserved. 0-13-140909-3
Top Operation
The top operation is to retrieve the value at the stack. A specification for
it is:
1. Receive: A stack object
2. Return: The value at top of the stack, provided the stack is nonempty
3. Output: An empty stack message if the stack is empty.

From the specification, it is clear that top () should be constant member function,
And so a prototype for it is:

StackElement top () const;

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 25
Education, Inc. All rights reserved. 0-13-140909-3
Top Operation for the stack
Class
In stack.cpp
StackElement stack::top() const
In Stack.h
{
Class Stack if (myTop >= 0)
{ return myArray [myTop];
/***** Function Members *****/ Cerr << ** Stack is empty ** \n;
Public: }
...
Stackelement top () const; Stack contents:
/***** data Members *****/ Modify test Driver 8
Private:
Cout << top value: << s.top () << endl;
6
... 4
}; // End of class declaration 2
// Definition of Class Constructor S empty? False
Output Top value: 8

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 26
Education, Inc. All rights reserved. 0-13-140909-3
Pop Operation
To remove the top stack element.
A specification for it is:
1. Receive: A stack object.
2. Return: The stack with its top value (if any ) removed.
3. Output: An empty stack message if the stack is empty.

This specification indicates that pop () should be a


nonconstant member function, so a prototype for it is
simple.

Void pop ()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 27
Education, Inc. All rights reserved. 0-13-140909-3
Algorithm for Pop
1. check if the stack is empty
2. if it is not empty then
Decrement myTop by 1.
Otherwise
Display a stack empty message.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 28
Education, Inc. All rights reserved. 0-13-140909-3
Pop Operation
In Stack.h In stack.cpp
Class Stack Void Stack :: pop ()
{ {
/***** Function Members *****/ if (myTop >=0)
Public: myTop --;
... else
Void pop (); cerr << ** stack is empty _ cant remove a value ** \n;
/***** data Members *****/
Private: Modify test Driver
...
}; // End of class declaration While (! S.empty ())
Stack Contents:
{ 8
cout << popping << s.top () << endl; 6
s.Pop (); 4
Cout<< s empty? << s. empty () << endl; 2
S empty? False
Top value :8
Popping 8
Popping 6
Output Popping 4
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson
Popping 2 29
Education, Inc. All rights reserved. 0-13-140909-3 S empty? true
Complete Stack Class
Const int STACK_CAPACITY = 128; /* Return value at top of the stack */
Typedef int StackElement; StackElement top () const;
Class Stack /* Remove value at top of the stack */
{ Void pop ();
/ ** Function Members **/
Public: /* Data Members */
/* Constructor */ Private :
Stack (); stackElement my Array [STACK_CAPACITY];
/* Is the stack empty */ Int myTop;
Bool empty () const; };
/* Add a value to the stack */ // end of the class declaration
Void push (const StackElement & value);
/* Display values stored in the stack */
Void display (ostream & out) const;

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 30
Education, Inc. All rights reserved. 0-13-140909-3
Implementation file, Stack.cpp //--- Definition of display()
void Stack::display(ostream & out) const {
#include <iostream> for (int i = myTop; i >= 0; i--)
using namespace std; out << myArray[i] << endl;
#include "Stack.h" }
//--- Stack constructor
Stack::Stack(): myTop(-1) { } //--- Definition of top()
StackElement Stack::top() const {
//--- Definition of empty() if ( !empty() )
bool Stack::empty() const { return (myArray[myTop]);
return (myTop == -1); else {
} cerr << "*** Stack is empty ;
return *(new StackElement);
//--- Definition of push() }
void Stack::push(const StackElement & value) }
{
if (myTop < STACK_CAPACITY - 1) { //--- Definition of pop()
++myTop; void Stack::pop()
myArray[myTop] = value; {
} else { if ( !empty() )
cerr << "*** Stack full ***\n; myTop--;
exit(1); else
} cerr << "*** Stack is empty -- "
} "can't remove a value ***\n";
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 31
Education, Inc. All rights reserved. 0-13-140909-3
#include <iostream> while (!s.empty()) {
#include <iomanip> cout << "Popping " << s.top()
using namespace std; << endl;
#include "Stack.h" s.pop();
}
int main() { cout << "Stack empty? "
Stack s; << s.empty() << endl;
cout << "Stack created. Empty? " cout << "Top value: " << s.top()
<< boolalpha << endl;
<< s.empty() << endl; cout << "Trying to pop: " << endl;
cout << "How many elements to add? "; s.pop();
int numItems; }
cin >> numItems;
for (int i = 1; i <= numItems; i++)
s.push(i);

cout << "Stack contents:\n";


s.display(cout);
cout << "Stack empty? " << s.empty()
<< endl;
cout << "Top value: " << s.top()
<< endl;
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 32
Education, Inc. All rights reserved. 0-13-140909-3
Notice

Stack.h Stack.cpp
Define the classes Define the main functions of stack
#include "Stack.h"
Public:
------------ Stack ()
------------ Empty ()
Push ()
Private: Display ()
------------ Top ()
------------ Pop()
Main program

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson 33
Education, Inc. All rights reserved. 0-13-140909-3

S-ar putea să vă placă și