Stack and Queue
Stack and Queue
STACK OVERVIEW
Stack
Basic operations of stack
Pushing, popping etc.
Implementations of stacks using
array
linked list
THE STACK ADT
top
B
top top
A A A
top
IMPLEMENTATION OF STACKS
Any list implementation could be used to implement a
stack
Arrays(static: the size of stack is given initially)
Linked lists (dynamic: never become full)
Pop
(1) Set return value to Stack[TopOfStack]
(2) Decrement TopOfStack by 1
Enqueue
Insert an element at the rear of the queue
Dequeue
Remove an element from the front of the queue
Remove Insert
(Dequeue) front rear (Enqueue)
IMPLEMENTATION OF QUEUE
Just as stacks can be implemented as arrays or linked
lists, so with queues.
Dynamic queues have the same advantages over static
queues as dynamic stacks have over static stacks
QUEUE IMPLEMENTATION OF ARRAY
Naïve way
When enqueuing, the front index is always fixed and the rear
index moves forward in the array.
When dequeuing, the element at the front the queue is removed.
Move all the elements after it by one position. (Inefficient!!!)
6 9 9
Recursive Implementation
int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
ou turn this into a program, you end up with functions that call
themselves
Iterative implementation
int Factorial(int n)
{
int fact = 1;
for(int count = 2; count <= n; count++)
fact = fact * count;
return fact;
}
RECURSION VS. ITERATION
Iteration can be used in place of recursion
An iterative algorithm uses a looping construct
A recursive algorithm uses a branching structure
Recursive solutions are often less efficient, in terms of
both time and space, than iterative solutions
Recursion can simplify the solution of a problem, often
resulting in shorter, more easily understood source code
HOW DO I WRITE A RECURSIVE
FUNCTION?
Determine the size factor
Determine the base case(s)
(the one for which you know the answer)
Determine the general case(s)
(the one where the problem is expressed as a smaller version
of itself)
Verify the algorithm
(use the "Three-Question-Method")
Recursive calls to f get pushed onto stack
Multiple copies of function f, each with different arguments &
local variable values, and at different lines in function