L5_Stack_Queue
L5_Stack_Queue
Applications
Numerous applications:
Parsing code:
Matching parenthesis
XML (e.g., XHTML)
Tracking function calls
Dealing with undo/redo operations
Reverse-Polish calculators
Assembly language
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D E F
0 1 2 3 4 TOP =5 6 7 8 9
Pop Operation
• The pop operation is used to delete the topmost element from the
stack.
• First check if TOP == -1.
If true then it means the stack is empty so no more deletions can
further be done, an UNDERFLOW message is printed.
If not true, get the value of the top element, decrease TOP by one.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D
0 1 2 TOP = 3 4 5 6 7 8 9
Peek Operation
• Peek is an operation that returns the value of the topmost
element of the stack without deleting it from the stack.
• he peep operation first checks if the stack is empty or contains
some elements.
• If TOP == -1, then an appropriate message is printed else the
value is returned.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
ulimit –s
ulimit –a
ulimit -s <new_size_in_kb>
pmap pid
PUSH-Operation
PUSH
top
top
POP
POP
top
top
Stack using Linked List
Push using Linked List
PUSH OPERATION
top
Stack
Operation
Pop using Linked List
POP OPERATION
top
Basic Idea
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum
size of the stack).
void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}
• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures
The Stock Span Problem
(given stock prices, day wise time series data)
Examples includes:
– Matching tags in XHTML
– In C++, matching
• parentheses ( ... )
• brackets, and [ ... ]
• braces { ... }
Parsing XHTML
You will use XHTML (and more generally XML and other markup
languages) in the workplace
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html> <head>
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html> <head>
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html> <body>
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html> <body>
Parsing XHTML
<html>
<head><title>Hello</title></head>
<body><p>This appears in the
<i>browser</i>.</p></body>
</html>
<html>
Parsing XHTML
Possible errors:
– a closing tag which does not match the opening tag on top of the stack
– a closing tag when the stack is empty
– the stack is not empty at the end of the document
Parsing C
operatorStack
Evaluating Postfix Expressions
operandStack
Infix and Postfix Notations
• Infix: operators placed between operands:
A+B*C
• Postfix: operands appear before their operators:-
ABC*+
• There are no precedence rules to learn in postfix notation, and parentheses
are never needed
Infix notation
Normally, mathematics is written using what we call in-fix notation:
(3 + 4) × 5 – 6
The operator is placed between to operands
http://www.audiovis.nac.gov.pl/
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E 2 * * A
3 ( *( A
becomes
4 B *( AB
ABCD*+*E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
is also called as 9 ) * ABCD*+
Reverse Polish 10 + + ABCD*+*
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
Prefix Notation
• In a prefix notation, the operator is placed before the operands.
• For example, if A+B is an expression in infix notation, then the
corresponding expression in prefix notation is given by +AB.
• While evaluating a prefix expression, the operators are applied to
the operands that are present immediately on the right of the
operator.
• Prefix expressions also do not follow the rules of operator
precedence, associativity, and even brackets cannot alter the
order of evaluation.
• The expression (A + B) * C is written as:
*+ABC in the prefix notation
Evaluation of an Infix Expression
STEP 1: Convert the infix expression into its equivalent postfix expression
Algorithm to convert an Infix notation into postfix notation
Step 1: Add ‘)” to the end of the infix expression
Step 2: Push “(“ on to the stack
Step 3: Repeat until each character in the infix notation is scanned
IF a “(“ is encountered, push it on the stack
IF an operand (whether a digit or an alphabet) is encountered,
add it to the postfix expression.
IF a “)” is encountered, then;
a. Repeatedly pop from stack and add it to the postfix expression until a “(” is
encountered.
b. Discard the “(“. That is, remove the “(“ from stack and do not
add it to the postfix expression
IF an operator X is encountered, then;
a Repeatedly pop from stack and add each operator (popped from the stack) to the
postfix expression which has the same precedence or a higher precedence than X
b. Push the operator X to the stack
Step 4: Repeatedly pop from the stack and add it to the postfix expression
until the stack is empty
Step 5: EXIT
Evaluation of an Infix Expression
• Step 1 infix “(9 - (( 3 * 4) + 8) / 4)" => postfix “9 3 4 * 8 + 4 / -“
* (-((* 93 * 9, 12
4 (-((* 934
8 9, 12, 8
) (-( 934*
+ 9, 20
+ (-(+ 934*
8 (-(+ 934*8 4 9, 20, 4
) (- 934*8+ / 9, 5
/ (-/ 934*8+
- 4
4 (-/ 934*8+4
) 934*8+4/-
Example
(5*(((9+8)*(4*6))+7))
• Input
598+46**7+*
• Evaluation
push(5)
push(9)
push(8)
push(pop() + pop())
push(4)
push(6)
push(pop() * pop())
push(7)
push(pop() + pop())
push(pop() * pop())
print(pop())
• What is the answer?
Reverse-Polish Notation
Other examples:
3 4 5 × + 6 –
3 20 + 6 –
23 6 –
17
3 4 5 6 – × +
3 4 –1 × +
3 –4 +
–1
Reverse-Polish Notation
Benefits:
– No ambiguity and no brackets are required
– It is the same process used by a computer to perform computations:
• operands must be loaded into registers before operations can be performed
on them
– Reverse-Polish can be processed using stacks
Reverse-Polish Notation
1
Reverse-Polish Notation
2
1
Reverse-Polish Notation
3
2
1
Reverse-Polish Notation
5
1
Reverse-Polish Notation
4
5
1
Reverse-Polish Notation
5
4
5
1
Reverse-Polish Notation
6
5
4
5
1
Reverse-Polish Notation
30
4
5
1
Reverse-Polish Notation
–26
5
1
Reverse-Polish Notation
7
–26
5
1
Reverse-Polish Notation
–182
5
1
Reverse-Polish Notation
–177
1
Reverse-Polish Notation
178
Reverse-Polish Notation
8
178
Reverse-Polish Notation
9
8
178
Reverse-Polish Notation
72
178
Reverse-Polish Notation
250
Reverse-Polish Notation
Thus
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +
evaluates to the value on the top: 250
The equivalent in-fix notation is
((1 – ((2 + 3) + ((4 – (5 × 6)) × 7))) + (8 × 9))
Incidentally,
1 – 2 + 3 + 4 – 5 × 6 × 7 + 8 × 9 = – 132
which has the reverse-Polish notation of
1 2 – 3 + 4 + 5 6 7 × × – 8 9 × +
A + B * C (A + (B * C)) (A + (B C *) ) A B C * +
Ans:598+46**7+*
• (6 * (5 + (2 + 3) * 8 + 3))
Ans: 6523+8*+3+*
• (a + b * c + (d * e + f) * g)
Ans: abc*+de*f+g*+
Standard Template Library
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> istack;
istack.push( 13 );
istack.push( 42 );
cout << "Top: " << istack.top() << endl;
istack.pop(); // no return value
cout << "Top: " << istack.top() << endl;
cout << "Size: " << istack.size() << endl;
return 0;
}
The Java Virtual Machine
1 Bread
2 Oranges
Front Back
3 Tortillas
Stack 4 Beans
5 Apples
6 Lettuce
7 Milk
Queue
ADT-Queue
Organizes entries in the order added
First-In, First-out (FIFO) Behavior
Entries are added at the back/rear
Removals occur at the front peekFront
Access restricted to entries dequeue enqueue
Only front entry is accessible
Earliest entry added to queue
front back(rear)
Queue Representation
ENQUEUE
front rear
Queue using Linked List
DEQUEUE
front rear
Example: Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};
struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;
if (q->qfront == NULL) {
q->qrear = NULL;
}
free(temp);
return dequeuedValue;
}
Problem With Array Implementation
• The size of the queue depends on the number and order of enqueue
and dequeue.
• It may be situation where memory is available but enqueue is not
possible.
ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N
front
front rearrear
There are four errors associated with this abstract data type:
* It is an undefined operation to access or pop from an empty deque
Deques
• A deque (double-ended queue) is a list in which
elements can be inserted or deleted at either end.
• Also known as a head-tail linked list because elements
can be added to or removed from the front (head) or
back (tail).
• A deque can be implemented either using a circular array
or a circular doubly linked list.
• In a deque, two pointers are maintained, LEFT and RIGHT
which point to either end of the deque.
Deque variants
• There are two variants of deques:
– Input restricted deque: In this dequeue insertions can be
done only at one of the ends while deletions can be done
from both the ends.
– Output restricted deque: In this dequeue deletions can be
done only at one of the ends while insertions can be done
on both the ends.
29 37 45 54 63
0 1 2 LEFT = 3 4 5 6 RIGHT = 7 8 9
63 27 18
42
RIGHT = 0 1 2 3 4 5 6 LEFT = 7 8 9
Priority Queues
• A priority queue is a queue in which each element is assigned a
priority.
• The priority of elements is used to determine the order in which
these elements will be processed.
• The general rule of processing elements of a priority queue can be
given as:
o An element with higher priority is processed before an element
with lower priority
o Two elements with same priority are processed on a first come
first served (FCFS) basis
• Priority queues are widely used in operating systems to execute the
highest priority process first.
• In computer’s memory priority queues can be represented using
arrays or linked lists.
Linked List Representation of Priority
Queues
• When a priority queue is implemented using a linked list, then
every node of the list contains three parts: (1) the information or
data part, (ii) the priority number of the element, (iii) and address
of the next element.
• If we are using a sorted linked list, then element having higher
priority will precede the element with lower priority.
A 1 B 2 C 3 D 3 E 4 X
A 1 B 2 C 3 D 3 E 4 F 4 X
Applications of Queues
1. Queues are widely used as waiting lists for a single
shared resource like printer, disk, CPU.
1 Bread
2 Oranges
Front Back
3 Tortillas
Stack 4 Beans
5 Apples
6 Lettuce
7 Milk
Queue