CSE 203-July2021-Stack-I
CSE 203-July2021-Stack-I
1
Stacks
Also called a last-in–first-out (LIFO) behaviour
– Graphically, we may view these operations as follows:
2
Stacks
LIFO: Last In, First Out.
Restricted form of list: Insert and remove
only at front of list.
Notation:
• Insert: PUSH
• Remove: POP
• The accessible element is called TOP.
3
Stack ADT
C++3elatestP121.pdf
4
Array-Based Stack
// Array-based stack implementation
private int maxSize; // Max size of stack
private int top; // Index for top
private E [] listArray;
Issues:
• Which end is the top?
• Where does “top” point to?
• What are the costs of the operations?
5
Array-Based Stack
TOP
Issues: 0 TOP 0
operations? 7 7
6
Array-Based Stack
Issues:
• Which end is the top?
– Option 1: At the beginning.
– Option 2: At the tail.
• Where does “top” point to?
– The first available position in the stack
• What are the costs of the operations?
– Option 1 is inefficient (why?)
• The last element must be at the beginning. So,
every time you push, you would need to shift the
items back.
– Option 2 is efficient (Why?).
7
Array-Based Stack
Issues:
• Which end is the top?
– Option 1: At the beginning.
– Option 2: At the tail.
• Where does “top” point to?
– The first available position in the stack
• What are the costs of the operations?
– Option 1 is inefficient (why?)
– Option 2 is efficient (Why?).
• Here, as the elements are pushed in, they are
appended at the tail.
• Method pop removes the tail element
8
Array Based Stack Implementation in C++
C++3elatestP122.pdf
9
Linked List Based Stack
1. Elements are inserted and removed only from the head of
the list.
2. A header node is not used because no special-case code is
required for lists of zero or one elements.
3. The only data member is top, a pointer to the first (top)
link node of the stack. Top is Null for empty stack.
10
Link Based Stack Implementation in C++
C++3elatestP124.pdf
11
Stack: Array-Based vs Linked Based
• All operations in both implementations take
constant time
• The space analysis is similar to that done for
list implementations.
– The array-based stack must declare a fixed-size
array initially, and some of that space is wasted
whenever the stack is not full.
– The linked stack can shrink and grow but requires
the overhead of a link field for every element.
12
One Array Two Stacks…
• Array based stack has a one-way growth. So, we can
implement two stacks in one
– Each grows inward from each end
• This may lead to less wasted space.
• However, this only works well
– when the space requirements of the two stacks are inversely
correlated: ideally when one stack grows, the other will shrink.
• This is particularly effective when elements are taken from
one stack and given to the other.
• If instead both stacks grow at the same time, then the free
space in the middle of the array will be exhausted quickly.
13
Replacing recursion with a stack
14
Replacing recursion with a stack
17
Stack Based ToH
C++3elatestP128.pdf
18