Stacks and Linked Lists

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 88

Stacks and Linked Lists

Abstract Data Types (ADTs)


• An ADT is an abstraction of a data structure that
specifies
– Data stored
– Operations on the data
– Error conditions associated with operations
Abstract Data Types (ADTs)
• An ADT is an abstraction of a data structure that
specifies
– Data stored
– Operations on the data
– Error conditions associated with operations
• Example: Registering for classes
– The data stored are the courses in your schedule
– The operations supported are
• Register(course)
• Unregister(course)
• ForceRequest(course)
– Error conditions:
• Registering for multiple classes meeting at the same time
Stacks
Stacks
• Stacks store arbitrary objects
(Pez in this case)
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
– pop(): removes and returns the top
element of the stack
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
– pop(): removes and returns the top
element of the stack
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
– pop(): removes and returns the top
element of the stack
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
– pop(): removes and returns the top
element of the stack
– top(): returns a reference to the
top element of the stack, but
doesn’t remove it
Stacks
• Stacks store arbitrary objects
(Pez in this case)
• Operations
– push(e): inserts an element to the
top of the stack
– pop(): removes and returns the top
element of the stack
– top(): returns a reference to the
top element of the stack, but
doesn’t remove it
• Optional operations
– size(): returns the number of
elements in the stack
– empty(): returns a bool indicating if
the stack contains any objects
Stack Exceptions
• Attempting to execute an operation of ADT may
cause an error condition called an exception
• Exceptions are said to be “thrown” by an
operation that cannot be executed
• In the Stack ADT, pop and top cannot be
performed if the stack is empty
• Attempting to execute pop or top on an empty
stack throws an EmptyStackException
Exercise: Stacks
• Describe the output and final structure of the stack after
the following operations:
– Push(8)
– Push(3)
– Pop()
– Push(2)
– Push(5)
– Pop()
– Pop()
– Push(9)
– Push(1)
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
C++ Run-time Stack
• The C++ run-time system keeps main() {
int i;
track of the chain of active
functions with a stack i = 5; bar
• When a function is called, the foo(i); PC = 1
m=6
run-time system pushes on the }
stack a frame containing foo(int j)
– Local variables and return value { foo
– Program counter, keeping track int k; PC = 3
of the statement being executed k = j+1; j=5
• When a function returns, its bar(k); k=6
frame is popped from the stack }
and control is passed to the
method on top of the stack bar(int m) main
{ PC = 2
… i=5
}
Array-based Stack
• A simple way of Algorithm size()
return t + 1
implementing the
Stack ADT uses an Algorithm empty()
array return size () == 0
• We add elements
Algorithm pop()
from left to right if empty() then
• A variable keeps track throw EmptyStackException
of the index of the else
tt1
top element return S[t + 1]


S
0 1 2 t
Array-based Stack (cont.)
• The array storing the
stack elements may
become full Algorithm push(e)
if t = S.length  1 then
• A push operation will throw FullStackException
then throw a else
FullStackException tt+1
– Limitation of the S[t]  e
array-based
implementation
– Not intrinsic to the
Stack ADT


S
0 1 2 t
Performance and Limitations
(array-based implementation of stack ADT)

• 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
Growable Array-based Stack
• In a push operation, when Algorithm push(o)
the array is full, instead of if t = S.length  1 then
A  new array of
throwing an exception, we size …
can replace the array with a for i  0 to t do
A[i]  S[i]
larger one SA
• How large should the new tt+1
S[t]  o
array be?
– incremental strategy:
increase the size by a
constant c
– doubling strategy: double
the size
Comparison

• We compare the incremental strategy and the


doubling strategy by analyzing the total time
T(n) needed to perform a series of n push
operations
• Assume that we start with an empty stack
represented by an array of size 1
• We call amortized time of a push operation
the average time taken by a push over the
series of operations, i.e., T(n)/n
Incremental Strategy Analysis

• We replace the array k = n/c times


• The total time T(n) of a series of n push
operations is proportional to
• n + c + 2c + 3c + 4c + … + kc =
• n + c(1 + 2 + 3 + … + k) =
• n + ck(k + 1)/2
• Since c is a constant, T(n) is O(n + k2) = O(n2)
• The amortized time of a push operation is O(n)
Doubling Strategy Analysis
• We replace the array k = log2 n times
• The total time T(n) of a series of n push
operations is proportional to
• n + 1 + 2 + 4 + 8 + …+ 2k =
• n  2k + 1 1 = 3n 1
• T(n) is O(n)
• The amortized time of a push operation is O(1)
Stack Interface in C++
template <class Type>
• Requires the class Stack {
public:
definition of class int size();
EmptyStackException bool isEmpty();
Type& top()
• Most similar STL throw(EmptyStackException);
construct is vector void push(Type e);
Type pop()
throw(EmptyStackException);
};
Array-based Stack in C++
template <class Type>
class ArrayStack
{
private:
int capacity; // stack capacity
Type *S; // stack array
int t; // top of stack

public:
ArrayStack(int c) : capacity(c) {
S = new Type [ capacity ];
t = -1;
}

bool isEmpty() { return t < 0; }

Type pop() throw(EmptyStackException) {


if ( isEmpty ( ) )
throw EmptyStackException(“Popping from empty stack”);
return S [ t-- ];
}
//… (other functions omitted)
Singly Linked List
• A singly linked list is a
structure consisting of a next
sequence of nodes
• A singly linked list stores
a pointer to the first
node (head) and last (tail) elem node

• Each node stores


– element tail
head
– link to the next node

Leonard Sheldon Howard Raj


Singly Linked List Node in C++
template <class Type> next
class SLinkedListNode {
public:
Type elem;
SLinkedListNode<Type> *next;
elem node
};

Leonard Sheldon Howard Raj


Singly Linked List
• A singly linked list is a structure consisting of a
sequence of nodes
• Operations
– insertFront(e): inserts an element on the front of
the list
– removeFront(): returns and removes the element
at the front of the list
– insertBack(e): inserts an element on the back of
the list
– removeBack(): returns and removes the element
at the end of the list
Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail

Leonard Sheldon Howard Raj


Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail

 

Penny Leonard Sheldon Howard Raj


Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail

Penny Leonard Sheldon Howard Raj


Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail

Penny Leonard Sheldon Howard Raj


Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail
 
Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node

head tail
 

Raj
Inserting at the Front
1. Allocate a new node
2. Have new node point to old head
3. Update head to point to new node
4. If tail is NULL, update tail to point to the head
node head tail

Raj
Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Leonard Sheldon Howard Raj


Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Leonard Sheldon Howard Raj


Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Leonard Sheldon Howard Raj


Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Leonard Sheldon Howard Raj


Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Sheldon Howard Raj


Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Sheldon
Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Sheldon
Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Sheldon
Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node

head tail

Sheldon
Removing at the Front

1. Update head to point to next node in the list


2. Return elem of previous head and delete the
node
3. If head is NULL, update tail to NULL
head tail
 
Inserting at the Back
1. Allocate a new node
2. If tail is NULL, update head and tail to point to
the new node; otherwise
1. Have the old tail point to the new node
2. Update tail to point to new node
head tail

Leonard Sheldon Howard


Inserting at the Back
1. Allocate a new node
2. If tail is NULL, update head and tail to point to
the new node; otherwise
1. Have the old tail point to the new node
2. Update tail to point to new node
head tail


Leonard Sheldon Howard

Raj
Inserting at the Back
1. Allocate a new node
2. If tail is NULL, update head and tail to point to
the new node; otherwise
1. Have the old tail point to the new node
2. Update tail to point to new node
head tail

Leonard Sheldon Howard Raj


Inserting at the Back
1. Allocate a new node
2. If tail is NULL, update head and tail to point to
the new node; otherwise
1. Have the old tail point to the new node
2. Update tail to point to new node
head tail

Leonard Sheldon Howard Raj


Removing at the Back
• No efficient way of doing so (O(n))
• Typically would not use a singly linked-list if this
operation is commonly used

head tail

Leonard Sheldon Howard Raj


Stack with a Singly Linked List
• We can implement a stack with a singly linked list
• The top element of the stack is the first node of the list
• The space used is O(n) and each operation of the Stack
ADT takes O(1) time

nodes

top t 

elements
Stack Summary
• Stack Operation Complexity for Different
Implementations
Array Array
Fixed-Size Expandable (doubling
Singly
Linked
strategy) List
Pop() O(1) O(1) O(1)

Push(o) O(1) O(n) Worst Case O(1)


O(1) Best Case
O(1) Average Case
Top() O(1) O(1) O(1)

Size(), isEmpty() O(1) O(1) O(1)


Queues
Queues
• Queues store arbitrary objects • Auxiliary queue operations:
• Insertions are at the end of the – front(): returns the element at
queue and removals are at the the front without removing it
front of the queue – size(): returns the number of
• Main queue operations: elements stored
– enqueue(e): inserts an element – isEmpty(): returns a boolean
at the end of the queue value indicating if there are no
– dequeue(): removes and returns elements in the queue
the element at the front of the
queue • Exceptions
– Attempting to execute dequeue
or front on an empty queue
throws an EmptyQueueException
Exercise: Queues
• Describe the output and final structure of the queue
after the following operations:
– enqueue(8)
– enqueue(3)
– dequeue()
– enqueue(2)
– enqueue(5)
– dequeue()
– dequeue()
– enqueue(9)
– enqueue(1)
Applications of Queues
• Direct applications
– Waiting lines
– Access to shared resources (e.g., printer)
– User input in a game
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
Array-based Queue
• Use an array of size N in a circular fashion
• Two variables keep track of the front and rear
– f index of the front element
– r index immediately past the rear element
• Array location r is kept empty
normal configuration
Q
0 1 2 f r

wrapped-around configuration
Q
0 1 2 r f
Queue Operations
• We use the Algorithm size()
return (N - f + r) mod N
modulo operator
Algorithm isEmpty()
(remainder of return (f = r)
division)

Q
0 1 2 f r

Q
0 1 2 r f
Queue Operations (cont.)
• Operation enqueue throws an Algorithm enqueue(o)
exception if the array is full if size() = N  1 then
throw FullQueueException
• This exception is
else
implementation-dependent
Q[r]  o
r  (r + 1) mod N

Q
0 1 2 f r

Q
0 1 2 r f
Queue Operations (cont.)
• Operation dequeue Algorithm dequeue()
throws an exception if isEmpty() then
if the queue is throw EmptyQueueException
else
empty o  Q[f]
• This exception is f  (f + 1) mod N
specified in the return o
queue ADT

Q
0 1 2 f r

Q
0 1 2 r f
Performance and Limitations
- array-based implementation of queue ADT

• Performance
– Let n be the number of elements in the queue
– The space used is O(n)
– Each operation runs in time O(1)
• Limitations
– The maximum size of the queue must be defined a
priori , and cannot be changed
– Trying to enqueue a new element into a full queue
causes an implementation-specific exception
Growable Array-based Queue
• In an enqueue operation, when the array is full,
instead of throwing an exception, we can
replace the array with a larger one
• Similar to what we did for an array-based stack
• The enqueue operation has amortized running
time
– O(n) with the incremental strategy
– O(1) with the doubling strategy
Exercise

• Describe how to implement a queue using a


singly-linked list
– Queue operations: enqueue(x), dequeue(),
size(), isEmpty()
– For each operation, give the running time
Queue with a Singly Linked List
• We can implement a queue with a singly linked list
– The front element is stored at the head of the list
– The rear element is stored at the tail of the list
• The space used is O(n) and each operation of the Queue ADT takes O(1)
time
• NOTE: we do not have the limitation of the array based implementation
on the size of the stack b/c the size of the linked list is not fixed, I.e., the
queue is NEVER full.

head tail

Leonard Sheldon Howard Raj


Informal C++ Queue Interface
template <class Type>
• Informal C++ class Queue {
public:
interface for our int size();
Queue ADT bool isEmpty();
Type& front()
• Requires the throw(EmptyQueueException);
void enqueue(Type e);
definition of class Type dequeue()
EmptyQueueException throw(EmptyQueueException);
};
• No corresponding
built-in STL class
Queue Summary
• Queue Operation Complexity for Different
Implementations
Array Array List
Fixed-Size Expandable (doubling Singly-
strategy) Linked
dequeue() O(1) O(1) O(1)

enqueue(o) O(1) O(n) Worst Case O(1)


O(1) Best Case
O(1) Average Case
front() O(1) O(1) O(1)

Size(), isEmpty() O(1) O(1) O(1)


Double-Ended Queues
• The Double-Ended Queue, or • Auxiliary deque operations:
Deque, ADT stores arbitrary – first(): returns the element at the
objects. (Pronounced ‘deck’)
front without removing it
• Richer than stack or queue ADTs.
Supports insertions and deletions – last(): returns the element at the
at both the front and the end. front without removing it
• Main deque operations: – size(): returns the number of
– insertFirst(object o): inserts elements stored
element o at the beginning of the – isEmpty(): returns a Boolean value
deque indicating whether no elements are
– insertLast(object o): inserts stored
element o at the end of the deque
– removeFirst(): removes and • Exceptions
returns the element at the front – Attempting to execute
of the deque removeFirst,removeLast, front, or
– removeLast(): removes and last on an empty deque throws an
returns the element at the end of EmptyDequeException
the deque
Doubly Linked List
• A doubly linked list is a structure
consisting of a sequence of
nodes prev next
• A doubly linked list stores a
pointer to a special head/tail
node elem
• Each node stores node
– element
– link to the prev, next node

head tail

Leonard Sheldon Howard Raj


Doubly Linked List
• A doubly linked list is a structure
consisting of a sequence of
nodes prev next
• A doubly linked list stores a
pointer to a special head/tail
node elem
• Each node stores node
– element
– link to the prev, next node

head tail
Doubly Linked List Node in C++
template <class Type>
class DLinkedListNode { prev next
public:
Type elem;
DLinkedListNode<Type> *prev, *next;
elem
}; node

head tail

Leonard Sheldon Howard Raj


Doubly Linked List
• A doubly linked list is a structure consisting of a
sequence of nodes
• Operations
– insertFront(e): inserts an element on the front of the list
– removeFront(): returns and removes the element at the
front of the list
– insertBack(e): inserts an element on the back of the list
– removeBack(): returns and removes the element at the end
of the list
• Private operations
– add(n, e): inserts the element after the node n
– remove(n): returns and removes the element stored in the
node n
Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

head tail

Leonard Sheldon Howard Raj


Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Bernadette
head tail

Leonard Sheldon Howard Raj


Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Bernadette
head tail

Leonard Sheldon Howard Raj


Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Bernadette
head tail

Leonard Sheldon Howard Raj


Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

head tail

Leonard Sheldon Howard Bernadette Raj


Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Sheldon
head tail
Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Sheldon
head tail
Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

Sheldon
head tail
Adding a Node
1. Allocate a new node
2. Have new node point to the previous and next
nodes
3. Update the previous and next nodes to point to
the new node

head tail

Sheldon
Removing a Node
1. Have the prev node’s next point to the next of
the current node
2. Have the next node’s prev point to the prev of
the current node
3. Delete the current node

head tail

Leonard Sheldon Howard Raj


Removing a Node
1. Have the prev node’s next point to the next of
the current node
2. Have the next node’s prev point to the prev of
the current node
3. Delete the current node

head tail

Leonard Sheldon Howard Raj


Removing a Node
1. Have the prev node’s next point to the next of
the current node
2. Have the next node’s prev point to the prev of
the current node
3. Delete the current node

head tail

Leonard Sheldon Howard Raj


Removing a Node
1. Have the prev node’s next point to the next of
the current node
2. Have the next node’s prev point to the prev of
the current node
3. Delete the current node

head tail

Leonard Sheldon Howard Raj


Removing a Node
1. Have the prev node’s next point to the next of
the current node
2. Have the next node’s prev point to the prev of
the current node
3. Delete the current node

head tail

Leonard Sheldon Raj


Deque with a Doubly Linked List
• We can implement a deque with a doubly linked list
– The front element is pointed to by head
– The rear element is pointed to by tail
• The space used is O(n) and each operation of the
Deque ADT takes O(1) time

head tail

Leonard Sheldon Howard Raj


Performance and Limitations
- doubly linked list implementation of deque ADT

• Performance
– Let n be the number of elements in the deque
– The space used is O(n)
– Each operation runs in time O(1)
• Limitations
– NOTE: we do not have the limitation of the array
based implementation on the size of the deque b/c
the size of the linked list is not fixed, I.e., the deque is
NEVER full.
Deque Summary
• Deque Operation Complexity for Different
Implementations
Array Array List List
Fixed- Expandable Singly- Doubly-
Size (doubling strategy) Linked Linked
removeFirst(), O(1) O(1) O(1) – O(1)
removeLast() removeFirst,
O(n) –
removeLast
insertFirst(o), O(1) O(n) Worst Case O(1) O(1)
InsertLast(o) O(1) Best Case
O(1) Average Case
first(), last O(1) O(1) O(1) O(1)

size(), O(1) O(1) O(1) O(1)


isEmpty()

You might also like