Docsity

Stack Data Structure: Implementation and Uses in Base-Two Conversion Algorithm, Slides of Algorithms and Programming

Partial preview of the text

Download Stack Data Structure: Implementation and Uses in Base-Two Conversion Algorithm and more Slides Algorithms and Programming in PDF only on Docsity!

Stacks

Introduction:

Consider the problems on pp. 170-

(1) Model the discard pile in a card

game

(2) Model a railroad switching

yard

(3) Parentheses checker

(4) Calculate and display base-

two representation

of base-ten numbers; e.g.,

Siding

Main Track

In the last problem:

Remainders are generated in right-to-left order. We need to

"stack" them up, then print them out from top to bottom.

In these problems we need a

"last-discarded-first-removed,"

"last-pushed-onto-first-removed,"

"last-stored-first-removed, "

"last-generated-first-displayed"

structured data type.

In summary ... a LIFO (Last-In-First-Out) structure.

LIFO

Example use of Stack

BASE-CONVERSION ALGORITHM

( See p. 171-2)

/* This algorithm displays the base-2 representation of a base-10 number. Receive: a positive integer number Output: the base-two representation of number. ---------------------------------------------------------------*/

  1. Create an empty stack to hold the remainders.

2. While number ≠ 0:

a. Calculate the remainder that results when number is divided by 2. b. Push remainder onto the stack of remainders. c. Replace number by the integer quotient of number divided by 2.

  1. While the stack of remainders is not empty: a. Retrieve and remove the remainder from the top of the stack of remainders. b. Display remainder.

Example (contd.)

do { cout << "Enter positive integer to convert: "; cin >> number; while (number != 0) { remainder = number % 2; stackOfRemainders.push(remainder); number /= 2; } cout << "Base-two representation: "; while (!stackOfRemainders.empty() ) { remainder = stackOfRemainders.top(); stackOfRemainders.pop(); cout << remainder; } cout << "\nMore (Y or N)? "; cin >> response; } while (response == 'Y' || response == 'y'); }

Building a Stack Class

Two steps:

1. Design the class; and

2. Implement the class.

Identify the operations needed to manipulate "real-world" objects

being modeled by class.

Operations are described:

Independent of class implementation.

In a manner independent of any specific representation of object

(because we have no idea what data members will be available).

1. Designing a Stack Class

2. Implementing a Stack Class

Define data members: consider storage structure(s) Attempt #1: Use an array with the top of the stack at position 0. e.g., Push 75, Push 89, Push 64, Pop

  • features: This models the operation of the stack of plates.
  • features: Not efficient to shift the array elements up and down in the array.

0 1 2 3 4

0 1 2 3 4

75

Push 75 0 1 2 3 4

89

Push 89 75

0 1 2 3 4

89

Push 64

75

64 0 1 2 3 4

89

Pop 75

Implementing Stack Class — Refined

Keep the bottom of stack at position 0. Maintain a "pointer" myTop to the top of the stack.

Instead of modeling a stack of plates, model a stack of books (or a discard pile in a card game.)

75 89

4 3 2 1 0

Push 75 Push 89

75

89

Push 64

75

64

Pop 4 3 2 1 0

4 3 2 1 0

4 3 2 1 0

4 3 2 1 0

89 75

64

myTop→

myTop→

myTop→ myTop→ myTop→

myTop = -1 myTop = 0 myTop = 1 myTop = 2 myTop = 1

Note: No moving of array elements.

Note: We don't clear this.

  1. typedef makes StackElement a synonym for int
  2. Want a stack of reals, or characters, or...? Change the typedef typedef double StackElementType; or typedef char StackElementType; or... When class library is recompiled, array elements will be double or char or...
  3. An alternative to using and changing a typedef: A template to build a Stack class is written whose element type is left unspecified. The element type is passed as a special kind of parameter at compile time. This is the approach used in the Standard Template Library ( STL ) and in most of the other C++ libraries.

Notes

  1. The typedef and declaration of STACK_CAPACITY outside the class declaration makes them: ♦ easy to find when they need changing ♦ accessible throughout the class and in any file that #includes Stack.h ♦ without qualification

If we put typedef of StackElement and declaration of the constant STACK_CAPACITY in public section of the class declaration, they can be accessed outside the class, but require qualification: Stack::StackElement Stack::STACK_CAPACITY (for class) s.STACK_CAPACITY (for object)

  1. If we were to make STACK_CAPACITY a data member, we would probably make it a static data member: static const int STACK_CAPACITY = 128; This makes it a property of the class usable by all class objects, but they do not have their own copies of STACK_CAPACITY.

#ifndef __STACK_H #define __STACK_H

const int STACK_CAPACITY = 128; typedef int StackElement;

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

... /***** Data Members *****/ private: StackElement myArray[STACK_CAPACITY]; int myTop; }; // end of class declaration ... #endif

Stack.h (contd.)

Stack's Function Members

Constructor :

class Stack { public: /*--- Constructor --- Precondition: A stack has been declared. Postcondition: Stack has been constructed as an empty stack. */ Stack(); ... } // end of class declaration

Simple

enough to

inline?

inline Stack::Stack() { myTop = -1; }

Yes

NOTE THE DOCUMENTATION

Receives Stack containing it as a function member (perhaps implicitly) Returns: True if stack is empty, false otherwise. Member function? (^) Yes

Yes

Const function? (Shouldn't alter data members)? Yes Simple enough to inline? class Stack { public:

... /* --- Is the Stack empty? ---

  • Returns: true if the Stack containing this
  • function is empty and false otherwise ***************************************************/ bool empty() const; ... };// end of class declaration

inline bool Stack::empty() const { return (myTop == -1); }

Empty Member Function

#include

#include

#include "Stack.h"

using namespace std;

int main()

Stack s;

cout << boolalpha << "s empty? "

<< s.empty() << endl;

Output:

s empty? true

or if boolalpha (an ostream switch) is omitted or

not implemented:

s empty? 1

Test Driver Program