Unit-2 Notes Stack Queue DKPJ-1
Unit-2 Notes Stack Queue DKPJ-1
1
PUSH OPeration on a Stack
PEEK Operation
Here the PEEK operation will return the value 7 without deleting it.
Representation of Stacks
Stack is usually represented by means of a linear array or a one-way linked list.
PEEK(STACK, TOP)
Algorithm Push(STACK,TOP)
1. If TOP=-1, then Print: UNDERFLOW, and Return
2. RETURN STACK[TOP]
int pop()
{
int val;
if (top == -1)
{
printf("\n STACK UNDERFLOW");
return -1;
}
else
{
val = st[top];
top--;
return val;
}
}
3
void display()
{
int i;
if (top == -1)
printf("\n STACK IS EMPTY");
else
{
for (i = top; i >= 0; i--)
printf("\n %d", st[i]);
}
}
int peek()
{
if (top == -1)
{
printf("\n STACK IS EMPTY");
return -1;
}
else
return (st[top]);
}
Push Example
POP Example
4
Linked Representation of Stack
The disadvantage of using an array to represent a stack is that the array must be specified to have a
fixed size. If the size of the array can’t be determined in advance, we can use the linked
representation of the stack.
The HEAD pointer of the linked list is used as the TOP of the stack.
The PUSH and POP operations can be implemented in a stack by the following algorithms.
PUSH_LINK(TOP, ITEM)
Algorithm PushLink(TOP,ITEM)
1. Allocate memory for the new node and name it as NEW
2. Set NEW->DATA=ITEM
3. IF TOP==NULL
SET NEW->NEXT=NULL
SET TOP=NEW
ELSE
SET NEW->NEXT=TOP
Set TOP=NEW
[END OF IF]
6. Exit.
The operation is the same as inserting a new node at the beginning of a linked list.
5
Block of code in C
void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}
POP_LINK(TOP, ITEM)
Algorithm PushLink(TOP,ITEM)
1. IF TOP=NULL then Write UNDERFLOW and Exit
2. Set ITEM=STACK->DATA
3. Set TEMP=TOP and TOP=TOP->LINK
4. FREE TEMP
5. Exit
The operation is the same as deleting a node from the beginning of a linked list.
6
Block of code in C
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
Block of code in C
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}
Applications of Stack
• Evaluating Expressions.
• Converting between expressions.
• Back tracking.
• Parsing context-free languages.
• Recursion removal.
• Tree and graph traversal.
7
Polish Notation
Algebraic expressions can be written using three separate but equivalent notations
namely infix, postfix, and prefix notations.
8
Example-1
Consider the following postfix notation
823*8+2/–
The equivalent infix expression is
8 – ((2 * 3) + 8) / 2
The following table shows the procedure for evaluating the expression by simulating the above
algorithm.
Example-2
Now let us consider the following infix expression 2 * (4+3) - 5.
Its equivalent postfix expression is 2 4 3 + * 5.
The following step illustrates how this postfix expression is evaluated.
9
Block of code in C
int i;
char ch;
int val;
int A, B;
push(ch);
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
A = pop();
B = pop();
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
}
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
10
The algorithm below converts an infix expression to a postfix expression.
Algorithm InfixToPostfix(Infix Expression)
1. Push "(" on to the stack, and add ")" to the end of infix expression.
2. Repeat until each character in the infix notation is scanned
• IF a "(" is encountered, push it on the stack.
• IF an operand is encountered, add it to the postfix expression.
• IF a ")" is encountered, then
1. Repeatedly pop from stack and add it to the postfix expression until a "(" is
encountered.
2. Discard the "(" . That is, remove the "(" from stack and do not add it to the
postfix expression.
• IF an operator O is encountered, then
1. 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 O.
2. Push the operator O to the stack.
3. Repeatedly pop from the stack and add it to the postfix expression until the stack is
empty.
Example-1
Convert the infix expression
A+ (B*C )
into postfix expression.
(
A ( A
+ (+ A
( (+( A
B (+( AB
* (+(* AB
C (+(* ABC
) ABC*+
11
Example -2
Converting an infix expression into a postfix expression.
Exercise:
Infix Prefix postfic
(A + B) × (C + D) × + AB + CD. ?
A × B + A × (B × D + C × E) + × AB × A + × BD × CE. ?
A × {B + C × (D + E)} / F × (G + H) / × A + B × C + DE × F + GH. ?
A×B+C×D+E×F ? AB × CD × + EF × +.
A – B + C × (D × E – F)} / G + H × K ? AB – C DE × F – × + G HK × + /.
12
Block of code in C
int covertInfixToPostfix (char *expression)
{
int i, j;
}
while (!isEmpty ())
expression[++j] = pop ();
expression[++j] = '\0';
printf ("%s", expression);
}
13
Factorial Function
To illustrate recursive functions, consider calculating the factorial of an integer.
The product of the positive integers from 1 to n is called n factorial denoted by
n!
. To find n!, multiply the number by the factorial of the number that is one less than the
number.
That is,
n! = n * (n - 1)!
Assume we need to find the value of 5!.
Then,
5! = 5 * 4!
, where
4! = 4 * 3!
Therefore,
5! = 5 * 4 * 3!
Expanding further, we get
5! = 5 * 4 * 3 * 2 * 1!
We can now write a recursive function that computes the factorial of a number. Here the
base case is when
n=1
, because the result will be 1 as
1! = 1
. The recursive case of the factorial function will call itself, but with a smaller value of n, as
factorial(n) = n factorial (n–1).
Tower of Hanoi
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower,[1] and sometimes pluralized)
is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes
which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of
size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple
rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
15
Queue
A Queue is a linear data structure in which deletions can only occur at one end, known as
the front, and insertions can only occur at the other end, known as the rear. It is similar to the
real-life queue where the first person entering the queue is the first person who comes out of the
queue. Thus queues are also called FIFO(First In First Out) lists.
Enqueue Operation
Inserting a new element in the position pointed by REAR is called the enqueue operation. We
must check if the queue is full before insertion. After the enqueue operation the REAR is
incremented by 1 and will point to the newly inserted element.
For inserting the first element in a queue, the value of FRONT has to be set to 0.
Consider a queue of size 5. Suppose we have to insert A, B, C, D and E into the queue. The
following changes will be made to the queue.
16
Enqueue Operation on a Queue
Dequeue Operation
Deleting an element in the position pointed by FRONT is called the dequeue operation. We must
check if the queue is empty before deletion. After the dequeue operation, the FRONT is
incremented by 1.
After deleting the last element in a queue, the value of FRONT and REAR has to be set to 0.
Consider the following example where we dequeue elements one by one until the queue becomes
empty.
17
Representation of Queues
Queue is usually represented in the computer using a linear array or a one-way linked list.
Array Representation of Queue
A queue can be represented in a program by using a linear array of elements and three pointer
variables FRONT, REAR and MAX.
The queue is empty if
FRONT = REAR = -1
.The queue is full if
FRONT =1
and
REAR = MAX - 1
The size of the above queue is 5. It has 3 elements A, B and C. The FRONT, REAR and MAX
pointers will have values 0, 2 and 5 respectively.
The algorithms for enqueue and dequeue operations are given below.
The algorithms for enqueue and dequeue operations are given below.
Algorithm: LINK_ENQUEUE
Step 1: Allocate memory for the new node and name it as PTR
Step 2: SET PTR -> DATA = VAL
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
Step 4: END
19
Inserting an element in a linked queue
Algorithm: LINK_DEQUEUE
Step 1: IF FRONT = NULL
Write Underflow
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: SET FRONT = FRONT -> NEXT
Step 4: FREE PTR
Step 5: END
Disadvantage of Queue
Look at the following queue.
You cannot insert a new value now, because the queue is completely full. Consider the following
case: two consecutive deletions are made.
20
Even though there is enough space to hold a new element, the overflow condition still occurs
since the condition
REAR = MAX – 1
is still valid. This is a major drawback of a linear queue. A solution to this problem is to make
the queue circular.
Types of Queues
A queue data structure can be classified into the following types:
• Circular Queue.
• Priority Queue.
• Dequeue.
Application of Queue
• Manage resource sharing such as CPU scheduling, disk scheduling..etc
• When data is sent and received between two processes asynchronously.
• Hadling of inrepputs in real time.
• Call waiting systems in call centers.
You cannot insert a new value now, because the queue is completely full. Consider the following
case: two consecutive deletions are made.
Even though there is enough space to hold a new element, the overflow condition still occurs
since the condition rear = MAX – 1 is still valid. This non-usable empty space is a major
drawback of a linear queue. A solution to this problem is to make the queue circular.
Circular Queue
A circular queue is a special type of queue where the last element is connected back to the
first element thus forming a circle. In the circular queue, the first index comes right after the
last index.
Enqueue Operation
Inserting a new element in the position pointed by REAR is called the enqueue operation.
• Print overflow and exit if the queue is full.
• For adding first element make
FRONT = 0
.
• Increment REAR by 1.
• Insert new element in the position pointed by REAR.
Algorithm: Enqueue
Step 1: IF FRONT = and Rear = MAX-1
Write OVERFLOW
Goto step 4
[End OF IF]
Step 2: IF FRONT=-1 and REAR=-1
SET FRONT = REAR = 0
ELSE IF REAR = MAX-1 and FRONT != 0
SET REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = ITEM
Step 4: EXIT
Dequeue Operation
Deleting an element in the position pointed by FRONT is called the dequeue operation. We must
check if the queue is empty before deletion.
• Print underflow and exit if the queue is empty.
• Return the value pointed by FRONT.
• Increment FRONT by 1 circularly.
• Set
FRONT = REAR = -1
for the last element.
22
Algorithm: Dequeue
Step 1: IF FRONT = -1
Write UNDERFLOW
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT
23
A priority queue is a collection of elements, in which each element has been assigned
a priority value. The order in which the elements will be processed is decided by the priority
of the element.
• An element with higher priority is processed first.
• If elements with the same priority occur, they are processed according to the order in
which they were added to the queue.
Usually, a lower priority number means higher priority.
24
If an element with the same priority as the new element already exists, the new element is put
after that element.
Deleting an element from a linked priority queue
The first node in the list will be deleted, and its data will be processed first.
Array Representation of Priority Queue
Priority queues can be also implemented using arrays. For each priority number, a separate
circular queue is used. Each queue will have its own FRONT and REAR pointers.
Take a look at the two-dimensional representation of a priority queue given below.
Kth row in matrix maintains the queue of elements with priority number k. FRONT[K] and
REAR[K] contain the FRONT and REAR elements of row K of the queue.
25