Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items...

27
Stacks

Transcript of Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items...

Page 1: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Stacks

Page 2: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first-out manner (LIFO).

This means that when a program retrieves an item from a stack, the last item inserted into the stack is the first one retrieved.

Similarly, the first item inserted is the last one retrieved (FILO).

Stack ADT

Page 3: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

first plate in, last plate out

Last plate in, first plate out

2345

1

Stack of Plates

The stack is a common data structure for representing things that need to maintained in a particular order. For instance, when a function calls another function, which in turn calls a third function, it's important that the third function return back to the second function rather than the first.

Stack ADT

Page 4: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

There are two kinds of stack data structure -

a) static, i.e. they have a fixed size, and are implemented as arrays.

b) dynamic, i.e. they grow in size as needed, and implemented as linked lists.

Static and Dynamic Stacks

Page 5: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

A stack has two primary operations, called push and pop.

a) The push operation causes a value to be stored (pushed) onto the stack.

e.g. if we have an empty integer stack with maximum capacity of3 items, we can perform the following 3 push operations -

push(5);push(10);push(15);

push() and pop()

Page 6: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

The pop operation retrieves (removes) an item from the stack.

If we execute 3 consecutive pop operations on the stack as shown above, we get the following results -

push() and pop()

Page 7: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Exceptions

Attempting the execution of an operation of an ADT may sometimes cause an error condition, called an exception. Exceptions are said to be “thrown” by an operation that cannot be executed.

In the Stack ADT, operation pop cannot be performed if the stack is empty

In the Stack ADT, operation push cannot be performed if the stack is full

Attempting the execution of pop on an empty stack, or a push on a full stack, throws an EmptyStackException

Page 8: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Stack Operations

Therefore, in order to simulate a stack functionality, the following operations need to be implemented.

– Main stack operations: push(object o): inserts element o pop(): removes and returns the last inserted element

– Auxiliary stack operations: top(): returns a reference to the last inserted element

without removing it size(): returns the number of elements stored isEmpty(): returns a Boolean value indicating whether no

elements are stored

Page 9: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Applications of Stacks

Direct applications– Page-visited history in a Web browser– Undo sequence in a text editor– Saving local variables when one function calls

another, and this one calls another, and so on.

Indirect applications– Auxiliary data structure for algorithms– Component of other data structures

Page 10: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

C++ Run-time Stack

The C++ run-time system keeps track of the chain of active functions with a stack

When a function is called, the run-time system pushes on the stack a frame containing

– Local variables and return value– Program counter, keeping track of

the statement being executed When a function returns, its frame is

popped from the stack and control is passed to the method on top of the stack

main() {int i = 5;foo(i);}

foo(int j) {int k;k = j+1;bar(k);}

bar(int m) {…}

bar PC = 1 m = 6

foo PC = 3 j = 5 k = 6

main PC = 2 i = 5

Page 11: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Array-based Stack

A simple way of implementing the Stack ADT uses an array

We add elements from left to right

A variable keeps track of the index of the top element

S0 1 2 t

Algorithm size()return t + 1

Algorithm pop()if isEmpty() then

throw EmptyStackException else

t t 1return S[t + 1]

Page 12: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Array-based Stack (cont.)

The array storing the stack elements may become full

A push operation will then throw a FullStackException

– Limitation of the array-based implementation

– Not intrinsic to the Stack ADT

S0 1 2 t

Algorithm push(o)if t = S.length 1 then

throw FullStackException else

t t + 1S[t] o

Page 13: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Performance and Limitations

Performance– Let n be the number of elements in the stack– The space used is O(n)– Each operation runs in time O(1)

Limitations– The maximum size of the stack must be defined a priori ,

and cannot be changed– Trying to push a new element into a full stack causes an

implementation-specific exception

Page 14: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Writing a program that uses an STL stack

Page 15: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Using a Stack in a Program

Requirement– Reverse a phrase that is input by the user

Steps in the process of creating the program1. Write a test

2. Write an algorithm

3. Write the program

4. Test the program Run an automated test – one way to test your

program

Page 16: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

1. Write a Test

Reverse "Go dog"

Reverse "Madam, I’m Adam"

Page 17: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

2. Write an Algorithm

//ALGORITHM main()

// Get the string s1

// Reverse the string

// Print the reversed string

Page 18: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

2. Write an Algorithm

//ALGORITHM main()

// Get the string s1

// Use a stack to reverse the string

// reverseString(s1)

// Print the reversed string

Page 19: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

2. Write an Algorithm

ALGORITHM reverseString(s1)Input: a stringOutput: the string reversed

Page 20: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

2. Write an Algorithm

ALGORITHM reverseString(s1)Input: a stringOutput: the string reversed

string s2stack stfor i = 0 to i = s1.length - 1

st.push(s1[i])while not st.empty()

s2 += st.top()st.pop()

return s2

Page 21: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Implementing a Data Structureas a Class

A Stack Example

Page 22: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Stack ADT

int size()Return the number of elements in the stack

bool isEmpty()Indicate whether the stack is empty

void push( Object element )Insert element at the top of the stack

Object top()Return the top element on the stack without removing it; an error occurs if the stack is empty.

Object pop()Remove and return the top element on the stack; an error occurs if the stack is empty

Page 23: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

To begin…

Open a header file and name it “ArrayStack.h”

Write the keyword “class” followed by the name of the class

class ArrayStack {

};

Add the curly braces, and remember the semicolon

Page 24: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Step 1 – Declare Public Operations

Declare member functions for all the public operations that are called for by the ADT(See p. 157 for the stack ADT.)

class ArrayStack {

public:

int size();

bool isEmpty();

void push( const char& c );

char& top();

void pop();

};

Access specifier All member functions after “public:” are accessible by any client in your program wherever there is an object of this class.

Page 25: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Step 2 – Declare Data Members

Next, decide how to hold the data that the data structure will contain. For example, you could put it into either an array or a linked list.

class ArrayStack {

private:

int capacity;//Maximum capacity of the array

char *pMyArray;//Pointer to an array

public:

int size();

bool isEmpty();

void push(const char& c);

char& top();

void pop();

};

Access specifier

All members after “private:” are only accessible to the member functions of this class.

Information hiding

Data members are always “private” so that the object’s client cannot change the data by accessing it directly.

Data can be accessed only by using the “public” member functions.

Page 26: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Step 3 – Define the Operations

Now, decide how to implement the operations

class ArrayStack {private:

int topIndex; int capacity; //Maximum capacity of the array

char *pMyArray; //Pointer to an arraypublic:

int size();bool isEmpty();void push(const char& c);char& top() { return pMyArray[topIndex]; }void pop();

};

Page 27: Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.

Step 4 – Add Exceptions etc.

Add robustness – use exceptions Avoid memory problems

– Implement a copy constructor– Implement operator=