0% found this document useful (0 votes)
42 views15 pages

CH 3 Stack and Queue - Docx-1

Chapter 3 discusses stacks and queues as linear data structures, with stacks operating on a LIFO principle and queues on a FIFO principle. It covers operations such as push and pop for stacks, and enQueue and deQueue for queues, along with their applications and implementations, including circular queues and deques. The chapter also highlights the importance of recursion in programming, explaining how recursive functions solve problems by breaking them down into smaller instances.

Uploaded by

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

CH 3 Stack and Queue - Docx-1

Chapter 3 discusses stacks and queues as linear data structures, with stacks operating on a LIFO principle and queues on a FIFO principle. It covers operations such as push and pop for stacks, and enQueue and deQueue for queues, along with their applications and implementations, including circular queues and deques. The chapter also highlights the importance of recursion in programming, explaining how recursive functions solve problems by breaking them down into smaller instances.

Uploaded by

Scopy OF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT

Stack and queue

What is a Stack?
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has
one end, whereas the Queue has two ends (front and rear). It contains only one pointer top
pointer pointing to the topmost element of the stack. Whenever an element is added in the
stack, it is added on the top of the stack, and the element can be deleted only from the stack. In
other words, a stack can be defined as a container in which insertion and deletion can be
done from the one end known as the top of the stack.

Some key points related to stack

o​ It is called as stack because it behaves like a real-world stack, piles of books, etc.
o​ A Stack is an abstract data type with a pre-defined capacity, which means that it can
store the elements of a limited size.
o​ It is a data structure that follows some order to insert and delete the elements, and that
order can be LIFO or FILO.

Working of Stack

Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.

Suppose we want to store the elements in a stack and let's assume that stack is empty. We
have taken the stack of size 5 as shown below in which we are pushing the elements one by
one until the stack becomes full.

Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it
goes from the top to the bottom when we were entering the new element in the stack. The stack
gets filled up from the bottom to the top.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
PUSH operation

The steps involved in the PUSH operation is given below:

o​ Before inserting an element in a stack, we check whether the stack is full.


o​ If we try to insert the element in a stack, and the stack is full, then the overflow condition
occurs.
o​ When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o​ When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o​ The elements will be inserted until we reach the max size of the stack.

POP operation

The steps involved in the POP operation is given below:

o​ Before deleting the element from the stack, we check whether the stack is empty.
o​ If we try to delete the element from the empty stack, then the underflow condition
occurs.
o​ If the stack is not empty, we first access the element which is pointed by the top
o​ Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue

Applications of Stack

The following are the applications of the stack:

o​ Balancing of symbols: Stack is used for balancing a symbol. For example, we have the
following program:
o​ Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of
the function are maintained.
o​ DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the
stack data structure.
o​ Backtracking: Suppose we have to create a path to solve a maze problem. If we are
moving in a particular path, and we realize that we come on the wrong way. In order to
come at the beginning of the path to create a new path, we have to use the stack data
structure.

Array implementation of Stack


In array implementation, the stack is formed by using the array. All the operations regarding the
stack are performed using arrays. Lets see how each operation can be implemented on the
stack using array data structure.

Adding an element onto the stack (push operation)


Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.

1.​ Increment the variable Top so that it can now refere to the next memory location.
2.​ Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.

Stack is overflown when we try to insert an element into a completely filled stack therefore, our
main function must always avoid stack overflow condition.

Algorithm:

1.​ begin
2.​ if top = n then stack full
3.​ top = top + 1
4.​ stack (top) : = item;
5.​ end

Deletion of an element from a stack (Pop operation)

Deletion of an element from the top of the stack is called pop operation. The value of the
variable top will be incremented by 1 whenever an item is deleted from the stack. The top most
element of the stack is stored in an another variable and then the top is decremented by 1. the
operation returns the deleted value that was stored in another variable as the result.

The underflow condition occurs when we try to delete an element from an already empty stack.

Algorithm :

1.​ begin
2.​ if top = 0 then stack empty;
3.​ item := stack(top);
4.​ top = top - 1;
5.​ end;

program to implement stack using array to push and pop element

1.​ #include <stdio.h>


2.​ int stack[100],i,j,choice=0,n,top=-1;
3.​ void push();
4.​ void pop();
5.​ void show();
6.​ void main ()
7.​ {
8.​
9.​ printf("Enter the number of elements in the stack ");
10.​ scanf("%d",&n);
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
11.​ printf("*********Stack operations using array*********");
12.​
13.​printf("\n----------------------------------------------\n");
14.​ while(choice != 4)
15.​ {
16.​ printf("Chose one from the below options...\n");
17.​ printf("\[Link]\[Link]\[Link]\[Link]");
18.​ printf("\n Enter your choice \n");
19.​ scanf("%d",&choice);
20.​ switch(choice)
21.​ {
22.​ case 1:
23.​ {
24.​ push();
25.​ break;
26.​ }
27.​ case 2:
28.​ {
29.​ pop();
30.​ break;
31.​ }
32.​ case 3:
33.​ {
34.​ show();
35.​ break;
36.​ }
37.​ case 4:
38.​ {
39.​ printf("Exiting....");
40.​ break;
41.​ }
42.​ default:
43.​ {
44.​ printf("Please Enter valid choice ");
45.​ }
46.​ };
47.​ }
48.​}
49.​
50.​void push ()
51.​{
52.​ int val;
53.​ if (top == n )
54.​ printf("\n Overflow");
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
55.​ else
56.​ {
57.​ printf("Enter the value?");
58.​ scanf("%d",&val);
59.​ top = top +1;
60.​ stack[top] = val;
61.​ }
62.​}
63.​
64.​void pop ()
65.​{
66.​ if(top == -1)
67.​ printf("Underflow");
68.​ else
69.​ top = top -1;
70.​}
71.​void show()
72.​{
73.​ for (i=top;i>=0;i--)
74.​ {
75.​ printf("%d\n",stack[i]);
76.​ }
77.​ if(top == -1)
78.​ {
79.​ printf("Stack is empty");
80.​ }
81.​}
Queue
1. A queue can be defined as an ordered list which enables insert operations to be performed at
one end called REAR and delete operations to be performed at another end called FRONT.

2. Queue is referred to be as First In First Out list.

3. For example, people waiting in line for a rail ticket form a queue.

Applications of Queue
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
Due to the fact that queue performs actions on first in first out basis which is quite fair for the
ordering of actions. There are various applications of queues discussed as below.

1.​ Queues are widely used as waiting lists for a single shared resource like printer, disk,
CPU.
2.​ Queues are used in asynchronous transfer of data (where data is not being transferred
at the same rate between two processes) for eg. pipes, file IO, sockets.
3.​ Queues are used as buffers in most of the applications like MP3 media player, CD
player, etc.
4.​ Queue are used to maintain the play list in media players in order to add and remove the
songs from the play-list.
5.​ Queues are used in operating systems for handling interrupts.

Circular Queue

Why was the concept of the circular queue introduced?

There was one limitation in the array implementation of Queue. If the rear reaches to the end
position of the Queue then there might be possibility that some vacant spaces are left in the
beginning which cannot be utilized. So, to overcome such limitations, the concept of the circular
queue was introduced.

As we can see in the above image, the rear is at the last position of the Queue and front is
pointing somewhere rather than the 0th position. In the above array, there are only two elements
and other three positions are empty. The rear is at the last position of the Queue; if we try to
insert the element then it will show that there are no empty spaces in the Queue. There is one
solution to avoid such wastage of memory space by shifting both the elements at the left and
adjust the front and rear end accordingly. It is not a practically good approach because shifting
all the elements will consume lots of time. The efficient approach to avoid the wastage of the
memory is to use the circular queue data structure.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
What is a Circular Queue?

A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out)
principle except that the last position is connected to the first position in a circular queue that
forms a circle. It is also known as a Ring Buffer.

Operations on Circular Queue

The following are the operations that can be performed on a circular queue:

o​ Front: It is used to get the front element from the Queue.


o​ Rear: It is used to get the rear element from the Queue.
o​ enQueue(value): This function is used to insert the new value in the Queue. The new
element is always inserted from the rear end.
o​ deQueue(): This function deletes an element from the Queue. The deletion in a Queue
always takes place from the front end.

Applications of Circular Queue

The circular Queue can be used in the following scenarios:

o​ Memory management: The circular queue provides memory management. As we have


already seen that in linear queue, the memory is not managed very efficiently. But in
case of a circular queue, the memory is managed efficiently by placing the elements in a
location which is unused.
o​ CPU Scheduling: The operating system also uses the circular queue to insert the
processes and then execute them.
o​ Traffic system: In a computer-control traffic system, traffic light is one of the best
examples of the circular queue. Each light of traffic light gets ON one by one after every
jinterval of time. Like red light gets ON for one minute then yellow light for one minute
and then green light. After green light, the red light gets ON.

Recursion
A Recursive function can be defined as a routine that calls itself directly or indirectly.
In other words, a recursive function is a function that solves a problem by solving smaller
instances of the same problem. This technique is commonly used in programming to solve
problems that can be broken down into simpler, similar subproblems.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue

Need of Recursive Function:


A recursive function is a function that solves a problem by solving smaller instances of the same
problem. This technique is often used in programming to solve problems that can be broken
down into simpler, similar subproblems.

What is a Deque (or double-ended queue)

The deque stands for Double Ended Queue. Deque is a linear data structure where the insertion
and deletion operations are performed from both ends. We can say that deque is a generalized
version of the queue.

Though the insertion and deletion in a deque can be performed on both ends, it does not follow
the FIFO rule. The representation of a deque is given as follows -

Types of deque

There are two types of deque -

o​ Input restricted queue


o​ Output restricted queue

Input restricted Queue

In input restricted queue, insertion operation can be performed at only one end, while deletion
can be performed from both ends.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue

Output restricted Queue

In output restricted queue, deletion operation can be performed at only one end, while insertion
can be performed from both ends.

Insertion at the front end

In this operation, the element is inserted from the front end of the queue. Before implementing
the operation, we first have to check whether the queue is full or not. If the queue is not full, then
the element can be inserted from the front end by using the below conditions -

o​ If the queue is empty, both rear and front are initialized with 0. Now, both will point to the
first element.
o​ Otherwise, check the position of the front if the front is less than 1 (front < 1), then
reinitialize it by front = n - 1, i.e., the last index of the array.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue

Insertion at the rear end

In this operation, the element is inserted from the rear end of the queue. Before implementing
the operation, we first have to check again whether the queue is full or not. If the queue is not
full, then the element can be inserted from the rear end by using the below conditions -

o​ If the queue is empty, both rear and front are initialized with 0. Now, both will point to the
first element.
o​ Otherwise, increment the rear by 1. If the rear is at last index (or size - 1), then instead of
increasing it by 1, we have to make it equal to 0.

Deletion at the front end


Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
In this operation, the element is deleted from the front end of the queue. Before implementing
the operation, we first have to check whether the queue is empty or not.

If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot perform the
deletion. If the queue is not full, then the element can be inserted from the front end by using the
below conditions -

If the deque has only one element, set rear = -1 and front = -1.

Else if front is at end (that means front = size - 1), set front = 0.

Else increment the front by 1, (i.e., front = front + 1).

Deletion at the rear end

In this operation, the element is deleted from the rear end of the queue. Before implementing
the operation, we first have to check whether the queue is empty or not.

If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot perform the
deletion.

If the deque has only one element, set rear = -1 and front = -1.

If rear = 0 (rear is at front), then set rear = n - 1.

Else, decrement the rear by 1 (or, rear = rear -1).


Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue

Applications of deque

o​ Deque can be used as both stack and queue, as it supports both operations.
o​ Deque can be used as a palindrome checker means that if we read the string from both
ends, the string would be the same.

What is a priority queue?


A priority queue is an abstract data type that behaves similarly to the normal queue except that
each element has some priority, i.e., the element with the highest priority would come first in a
priority queue. The priority of the elements in a priority queue will determine the order in which
elements are removed from the priority queue.

The priority queue supports only comparable elements, which means that the elements are
either arranged in an ascending or descending order.

For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue
with an ordering imposed on the values is from least to the greatest. Therefore, the 1 number
would be having the highest priority while 22 will be having the lowest priority.

Characteristics of a Priority queue

A priority queue is an extension of a queue that contains the following characteristics:

o​ Every element in a priority queue has some priority associated with it.
o​ An element with the higher priority will be deleted before the deletion of the lesser
priority.
o​ If two elements in a priority queue have the same priority, they will be arranged using the
FIFO principle.

Let's understand the priority queue through an example.

We have a priority queue that contains the following values:


Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
1, 3, 4, 8, 14, 22

All the values are arranged in ascending order. Now, we will observe how the priority queue will
look after performing the following operations:

Types of Priority Queue

There are two types of priority queue:

o​ Ascending order priority queue: In ascending order priority queue, a lower priority
number is given as a higher priority in a priority. For example, we take the numbers from
1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e.,
1 is given as the highest priority in a priority queue.​

o​ Descending order priority queue: In descending order priority queue, a higher priority
number is given as a higher priority in a priority. For example, we take the numbers from
1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e.,
5 is given as the highest priority in a priority queue.​

Representation of priority queue

Now, we will see how to represent the priority queue through a one-way list.
Data structure CHAPTER 3​ ​ PREPARED BY:URVI VASANT
Stack and queue
We will create the priority queue by using the list given below in which INFO list contains the
data elements, PRN list contains the priority numbers of each data element available in
the INFO list, and LINK basically contains the address of the next node.

Let's create the priority queue step by step.

In the case of priority queue, lower priority number is considered the higher priority,
i.e., lower priority number = higher priority.

Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted in
the list as shown in the below diagram:

Step 2: After inserting 333, priority number 2 is having a higher priority, and data values
associated with this priority are 222 and 111. So, this data will be inserted based on the FIFO
principle; therefore 222 will be added first and then 111.

Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and data
elements associated with 4 priority numbers are 444, 555, 777. In this case, elements would be
inserted based on the FIFO principle; therefore, 444 will be added first, then 555, and then 777.

Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and the
value associated with priority 5 is 666, so it will be inserted at the end of the queue.

You might also like