0% found this document useful (0 votes)
46 views62 pages

CSCE 3110 Data Structures & Algorithm Analysis: Stacks and Queues Reading: Chap.3 Weiss

The document summarizes key concepts about stacks and queues. It discusses what a stack is, the LIFO principle, stack applications like program execution and expression evaluation, and common stack operations like push, pop, isEmpty, and isFull. It also provides examples of array-based and list-based stack implementations and analyzes the time complexity of common stack operations. Finally, it covers the Towers of Hanoi problem as a classic stack application and provides pseudocode for its recursive solution.

Uploaded by

sanju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views62 pages

CSCE 3110 Data Structures & Algorithm Analysis: Stacks and Queues Reading: Chap.3 Weiss

The document summarizes key concepts about stacks and queues. It discusses what a stack is, the LIFO principle, stack applications like program execution and expression evaluation, and common stack operations like push, pop, isEmpty, and isFull. It also provides examples of array-based and list-based stack implementations and analyzes the time complexity of common stack operations. Finally, it covers the Towers of Hanoi problem as a classic stack application and provides pseudocode for its recursive solution.

Uploaded by

sanju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

CSCE 3110

Data Structures &


Algorithm Analysis

Stacks and Queues


Reading: Chap.3 Weiss
Stacks

Stack: what is it?


ADT
Applications
Implementation(s)
What is a stack?

Stores a set of elements in a particular order


Stack principle: LAST IN FIRST OUT
= LIFO
It means: the last element inserted is the first one to
be removed
Example

Which is the first element to pick up?


Last In First Out

E top
D top D D
C top C C C
B top B B B B
A top A A A A A
Stack Applications

Real life
Pile of books
Plate trays
More applications related to computer science
Program execution stack (read more from your text)
Evaluating expressions
Stack ADT

objects: a finite ordered list with zero or more elements.


methods:
for all stack  Stack, item  element, max_stack_size
 positive integer
Stack createS(max_stack_size) ::=
create an empty stack whose maximum size is
max_stack_size
Boolean isFull(stack, max_stack_size) ::=
if (number of elements in stack == max_stack_size)
return TRUE
else return FALSE
Stack push(stack, item) ::=
if (IsFull(stack)) stack_full
else insert item into top of stack and return
Stack ADT (cont’d)

Boolean isEmpty(stack) ::=


if(stack == CreateS(max_stack_size))
return TRUE
else return FALSE
Element pop(stack) ::=
if(IsEmpty(stack)) return
else remove and return the item on the top
of the stack.
Array-based Stack
Implementation
Allocate an array of some size (pre-defined)
Maximum N elements in stack
Bottom stack element stored at element 0
last index in the array is the top
Increment top when one element is pushed,
decrement after pop
Stack Implementation:
CreateS, isEmpty, isFull

Stack createS(max_stack_size) ::=


#define MAX_STACK_SIZE 100 /* maximum stack size */
typedef struct {
int key;
/* other fields */
} element;
element stack[MAX_STACK_SIZE];
int top = -1;

Boolean isEmpty(Stack) ::= top< 0;

Boolean isFull(Stack) ::= top >= MAX_STACK_SIZE-1;


Push

void push(int *top, element item)


{
/* add an item to the global stack */
if (*top >= MAX_STACK_SIZE-1) {
stack_full( );
return;
}
stack[++*top] = item;
}
Pop

element pop(int *top)


{
/* return the top element from the stack */
if (*top == -1)
return stack_empty( ); /* returns and error key */
return stack[(*top)--];
}
List-based Stack
Implementation: Push
void push(pnode top, element item)
{
/* add an element to the top of the stack */
pnode temp =
(pnode) malloc (sizeof (node));
if (IS_FULL(temp)) {
fprintf(stderr, “ The memory is full\n”);
exit(1);
}
temp->item = item;
temp->next= top;
top= temp;
}
Pop
element pop(pnode top) {
/* delete an element from the stack */
pnode temp = top;
element item;
if (IS_EMPTY(temp)) {
fprintf(stderr, “The stack is empty\n”);
exit(1);
}
item = temp->item;
top = temp->next;
free(temp);
return item;
}
Algorithm Analysis

push O(?)
pop O(?)
isEmpty O(?)
isFull O(?)

What if top is stored at the beginning of the


array?
A Legend
The Towers of Hanoi
In the great temple of Brahma in Benares, on a
brass plate under the dome that marks the center of
the world, there are 64 disks of pure gold that the
priests carry one at a time between these diamond
needles according to Brahma's immutable law: No
disk may be placed on a smaller disk. In the begging
of the world all 64 disks formed the Tower of
Brahma on one needle. Now, however, the process of
transfer of the tower from one needle to another is in
mid course. When the last disk is finally in place,
once again forming the Tower of Brahma but on a
different needle, then will come the end of the world
and all will turn to dust.
The Towers of Hanoi
A Stack-based Application
GIVEN: three poles
a set of discs on the first pole, discs of different sizes, the
smallest discs at the top
GOAL: move all the discs from the left pole to the right one.
CONDITIONS: only one disc may be moved at a time.
A disc can be placed either on an empty pole or on top of a
larger disc.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi – Recursive
Solution
void hanoi (int discs,
Stack fromPole,
Stack toPole,
Stack aux) {
Disc d;
if( discs >= 1) {
hanoi(discs-1, fromPole, aux, toPole);
d = fromPole.pop();
toPole.push(d);
hanoi(discs-1,aux, toPole, fromPole);
}
Applications

Infix to Postfix conversion


[Evaluation of Expressions]
Is the End of the World
Approaching?
Problem complexity 2n
64 gold discs
Given 1 move a second
Evaluation of Expressions
X=a/b-c+d*e-a*c

a = 4, b = c = 2, d = e = 3

Interpretation 1:
((4/2)-2)+(3*3)-(4*2)=0 + 8+9=1

Interpretation 2:
(4/(2-2+3))*(3-4)*2=(4/3)*(-1)*2=-2.66666…
How to generate the machine instructions
corresponding to a given expression?
precedence rule + associative rule
Token Operator Precedence1 Associativity

() function call 17 left-to-right


[] array element
-> . struct or union member
-- ++ increment, decrement2 16 left-to-right

-- ++ decrement, increment3 15 right-to-left


! logical not
- one’s complement
-+ unary minus or plus
&* address or indirection
sizeof size (in bytes)
(type) type cast 14 right-to-left

*/% mutiplicative 13 Left-to-right


+- binary add or subtract 12 left-to-right

<< >> shift 11 left-to-right

> >= relational 10 left-to-right


< <=
== != equality 9 left-to-right

& bitwise and 8 left-to-right

^ bitwise exclusive or 7 left-to-right

bitwise or 6 left-to-right

&& logical and 5 left-to-right

 logical or 4 left-to-right
?: conditional 3 right-to-left

= += -= assignment 2 right-to-left
/= *= %=
<<= >>=
&= ^= =

, comma 1 left-to-right
user compiler

Infix Postfix
2+3*4 234*+
a*b+5 ab*5+
(1+2)*7 12+7*
a*b/c ab*c/
(a/(b-c+d))*(e-a)*c abc-d+/ea-*c*
a/b-c+d*e-a*c ab/c-de*+ac*-

Postfix: no parentheses, no precedence


Token Stack Top
[0] [1] [2]
6 6 0
2 6 2 1
/ 6/2 0
3 6/2 3 1
- 6/2-3 0
4 6/2-3 4 1
2 6/2-3 4 2 2
* 6/2-3 4*2 1
+ 6/2-3+4*2 0
Infix to Postfix
Assumptions:
operators: +, -, *, /, %
operands: single digit integer

#define MAX_STACK_SIZE 100 /* maximum stack size */


#define MAX_EXPR_SIZE 100 /* max size of expression */
typedef enum{1paran, rparen, plus, minus, times, divide,
mod, eos, operand} precedence;
int stack[MAX_STACK_SIZE]; /* global stack */
char expr[MAX_EXPR_SIZE]; /* input string */
Evaluation of Postfix Expressions
int eval(void)
{
/* evaluate a postfix expression, expr, maintained as a
global variable, ‘\0’ is the the end of the expression.
The stack and top of the stack are global variables.
get_token is used to return the token type and
the character symbol. Operands are assumed to be single
character digits */
precedence token;
char symbol; int op1, op2;
int n = 0; /* counter for the expression string */
int top = -1;
token = get_token(&symbol, &n);
while (token != eos) {
if (token == operand)
push(&top, symbol-’0’); /* stack insert */
else { /* remove two operands, perform operation, and
return result to the stack */
op2 = pop(&top); /* stack delete */
op1 = pop(&top);
switch(token) {
case plus: push(&top, op1+op2); break;
case minus: push(&top, op1-op2); break;
case times: push(&top, op1*op2); break;
case divide: push(&top, op1/op2); break;
case mod: push(&top, op1%op2);
}
}
token = get_token (&symbol, &n);
}
return pop(&top); /* return result */
}
precedence get_token(char *symbol, int *n)
{
/* get the next token, symbol is the character
representation, which is returned, the token is
represented by its enumerated value, which
is returned in the function name */

*symbol =expr[(*n)++];
switch (*symbol) {
case ‘(‘ : return lparen;
case ’)’ : return rparen;
case ‘+’: return plus;
case ‘-’ : return minus;
case ‘/’ : return divide;
case ‘*’ : return times;
case ‘%’ : return mod;
case ‘\0‘ : return eos;
default : return operand;
/* no error checking, default is operand */
}
}
Infix to Postfix Conversion
(Intuitive Algorithm)
(1) Fully parenthesized expression
a / b - c + d * e - a * c -->
((((a / b) - c) + (d * e)) – (a * c))

(2) All operators replace their corresponding right


parentheses.
((((a / b) - c) + (d * e)) – (a * c))

/ - +* -*
(3) Delete all parentheses.
ab/c-de*+ac*-
two passes
The orders of operands in infix and postfix are the same.
a + b * c, * > +

Token Stack Top Output


[0] [1] [2]
a -1 a
+ + 0 a
b + 0 ab
* + * 1 ab
c + * 1 abc
eos -1 abc*=
a *1 (b +c) *2 d

Token Stack Top Output


[0] [1] [2]
a -1 a
*1 *1 0 a
( *1 ( 1 a
b *1 ( 1 ab
+ *1 ( + 2 ab
c *1 ( + )
match 2 abc
) *1 *1 = *2 0 abc+
*2 *2 0 abc+*1
d *2 0 abc+*1d
eos *2 0 abc+*1d*2
Rules

(1) Operators are taken out of the stack as long as their


in-stack precedence is higher than or equal to the
incoming precedence of the new operator.

(2) ( has low in-stack precedence, and high incoming


precedence.

( ) + - * / % eos
isp 0 19 12 12 13 13 13 0
icp 20 19 12 12 13 13 13 0
precedence stack[MAX_STACK_SIZE];
/* isp and icp arrays -- index is value of precedence
lparen, rparen, plus, minus, times, divide, mod, eos */
static int isp [ ] = {0, 19, 12, 12, 13, 13, 13, 0};
static int icp [ ] = {20, 19, 12, 12, 13, 13, 13, 0};

isp: in-stack precedence


icp: incoming precedence
Infix to Postfix
void postfix(void)
{
/* output the postfix of the expression. The expression
string, the stack, and top are global */
char symbol;
precedence token;
int n = 0;
int top = 0; /* place eos on stack */
stack[0] = eos;
for (token = get _token(&symbol, &n); token != eos;
token = get_token(&symbol, &n)) {
if (token == operand)
printf (“%c”, symbol);
else if (token == rparen ){
Infix to Postfix (cont’d)
/*unstack tokens until left parenthesis */
while (stack[top] != lparen)
print_token(delete(&top));
pop(&top); /*discard the left parenthesis */
}
else{
/* remove and print symbols whose isp is greater
than or equal to the current token’s icp */
while(isp[stack[top]] >= icp[token] )
print_token(delete(&top));
push(&top, token);
}
}
while ((token = pop(&top)) != eos)
print_token(token);
print(“\n”);
Queue
Stores a set of elements in a particular order
Stack principle: FIRST IN FIRST OUT
= FIFO
It means: the first element inserted is the first
one to be removed
Example

The first one in line is the first one to be


served
Queue Applications

Real life examples


Waiting in line
Waiting on hold for tech support
Applications related to Computer Science
Threads
Job scheduling (e.g. Round-Robin algorithm for
CPU allocation)
First In First Out

D rear
C rear C D rear
B rear B B C
rear front A front
A A front A front B
front
Applications: Job Scheduling
front rear Q[0] Q[1] Q[2] Q[3] Comments
-1 -1 queue is empty
-1 0 J1 Job 1 is added
-1 1 J1 J2 Job 2 is added
-1 2 J1 J2 J3 Job 3 is added
0 2 J2 J3 Job 1 is deleted
1 2 J3 Job 2 is deleted
Queue ADT
objects: a finite ordered list with zero or more elements.
methods:
for all queue  Queue, item  element,
max_ queue_ size  positive integer
Queue createQ(max_queue_size) ::=
create an empty queue whose maximum size is
max_queue_size
Boolean isFullQ(queue, max_queue_size) ::=
if(number of elements in queue == max_queue_size)
return TRUE
else return FALSE
Queue Enqueue(queue, item) ::=
if (IsFullQ(queue)) queue_full
else insert item at rear of queue and return queue
Queue ADT (cont’d)

Boolean isEmptyQ(queue) ::=


if (queue ==CreateQ(max_queue_size))
return TRUE
else return FALSE
Element dequeue(queue) ::=
if (IsEmptyQ(queue)) return
else remove and return the item at front of queue.
Array-based Queue
Implementation
As with the array-based stack
implementation, the array is of fixed size
A queue of maximum N elements
Slightly more complicated
Need to maintain track of both front and rear

Implementation 1

Implementation 2
Implementation 1:
createQ, isEmptyQ, isFullQ
Queue createQ(max_queue_size) ::=
# define MAX_QUEUE_SIZE 100/* Maximum queue size */
typedef struct {
int key;
/* other fields */
} element;
element queue[MAX_QUEUE_SIZE];
int rear = -1;
int front = -1;
Boolean isEmpty(queue) ::= front == rear
Boolean isFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1
Implementation 1:
enqueue

void enqueue(int *rear, element item)


{
/* add an item to the queue */
if (*rear == MAX_QUEUE_SIZE_1) {
queue_full( );
return;
}
queue [++*rear] = item;
}
Implementation 1:
dequeue

element dequeue(int *front, int rear)


{
/* remove element at the front of the queue */
if ( *front == rear)
return queue_empty( ); /* return an error key */
return queue [++ *front];
}
Implementation 2:
Wrapped Configuration
EMPTY QUEUE
[2] [3] [2] [3]
J2 J3

[1] [4] [1] J1 [4]

[0] [5] [0] [5]

front = 0 front = 0
rear = 0 rear = 3

Can be seen as a circular queue


Leave one empty space when queue is full
Why?
FULL QUEUE FULL QUEUE

[2] [3] [2] [3]


J2 J3 J8 J9

[1] J1 J4 [4][1] J7 [4]

J5 J6 J5

[0] [5] [0] [5]

front =0 front =4
rear = 5 rear =3
How to test when queue is empty?
How to test when queue is full?
Enqueue in a Circular Queue

void enqueue(int front, int *rear, element item)


{
/* add an item to the queue */
*rear = (*rear +1) % MAX_QUEUE_SIZE;
if (front == *rear) /* reset rear and print error */
return;
}
queue[*rear] = item;
}
Dequeue from Circular Queue
element dequeue(int* front, int rear)
{
element item;
/* remove front element from the queue and put it in item */
if (*front == rear)
return queue_empty( );
/* queue_empty returns an error key */
*front = (*front+1) % MAX_QUEUE_SIZE;
return queue[*front];
}
List-based Queue
Implementation: Enqueue
void enqueue(pnode &front, pnode rear, element item)
{ /* add an element to the rear of the queue */
pnode temp =
(pnode) malloc(sizeof (queue));
if (IS_FULL(temp)) {
fprintf(stderr, “ The memory is full\n”);
exit(1);
}
temp->item = item;
temp->next= NULL;
if (front) { (rear) -> next= temp;}
else front = temp;
rear = temp; }
Dequeue
element dequeue(pnode &front) {
/* delete an element from the queue */
pnode temp = front;
element item;
if (IS_EMPTY(front)) {
fprintf(stderr, “The queue is empty\n”);
exit(1);
}
item = temp->item;
front = temp->next;
free(temp);
return item;
}
Algorithm Analysis

enqueue O(?)
dequeue O(?)
size O(?)
isEmpty O(?)
isFull O(?)

What if I want the first element to be always


at Q[0] ?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy