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

Stack Queue

The document discusses stacks, which are linear data structures that follow the LIFO (last-in, first-out) principle. A stack has one end and contains a single top pointer pointing to the topmost element. Elements are added to the top of the stack and can only be removed from the top. Common stack operations include push, which adds an element to the top, and pop, which removes the top element. Stacks are used for applications like expression conversion, recursion, backtracking, and memory management.

Uploaded by

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

Stack Queue

The document discusses stacks, which are linear data structures that follow the LIFO (last-in, first-out) principle. A stack has one end and contains a single top pointer pointing to the topmost element. Elements are added to the top of the stack and can only be removed from the top. Common stack operations include push, which adds an element to the top, and pop, which removes the top element. Stacks are used for applications like expression conversion, recursion, backtracking, and memory management.

Uploaded by

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

What is a Stack?

A Stack is a linear data structure that follows


the LIFO (Last-In-First-Out) principle.

Stack has one end, 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
Stack of Books
Some key points related to stack

It is called as stack because it behaves like a real-


world stack, piles of books, etc.

A Stack is an abstract data type with a pre-defined


capacity, which means that it can store the elements
of a limited size.

It is a data structure that follows some order to


insert and delete the elements, and that order can be
LIFO or FILO.
Abstract Data type (ADT) is a type (or class) for
objects whose behaviour is defined by a set of values
and a set of operations.

The definition of ADT only mentions what operations


are to be performed but not how these operations will
be implemented.

It does not specify how data will be organized in


memory and what algorithms will be used for
implementing the operations.

It is called “abstract” because it gives an


implementation-independent view.
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.
Standard Stack Operations

The following are some common operations


implemented on the stack:

push(): When we insert an element in a stack then the


operation is known as a push. If the stack is full then the
overflow condition occurs.

pop(): When we delete an element from the stack, the


operation is known as a pop. If the stack is empty means
that no element exists in the stack, this state is known as
an underflow state.
isEmpty(): It determines whether the stack is empty or
not.
isFull(): It determines whether the stack is full or
not.‘

peek(): It returns the element at the given position.

count(): It returns the total number of elements


available in a stack.

change(): It changes the element at the given


position.

display(): It prints all the elements available in the


stack.
PUSH operation

The steps involved in the PUSH operation is given below:

Before inserting an element in a stack, we check whether the


stack is full.
If we try to insert the element in a stack, and the stack is full,
then the overflow condition occurs.

When we initialize a stack, we set the value of top as -1 to check


that the stack is empty.

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.

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:


Before deleting the element from the stack, we check
whether the stack is empty.

If we try to delete the element from the empty stack, then


the underflow condition occurs.

If the stack is not empty, we first access the element which


is pointed by the top.

Once the pop operation is performed, the top is


decremented by 1, i.e., top=top-1.
The following are the applications of the stack:

Balancing of symbols: Stack is used for balancing a symbol.


For example, we have the following program:
int main()
{
cout<<"Hello";
cout<<"javaTpoint";
}
As we know, each program has an
opening and closing braces; when the opening braces come,
we push the braces in a stack, and when the closing braces
appear, we pop the opening braces from the stack. Therefore,
the net value comes out to be zero. If any symbol is left in the
stack, it means that some syntax occurs in a program.
String reversal: Stack is also used for reversing a string. For
example, we want to reverse a "javaTpoint" string, so we can
achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we
reach the null character.
After pushing all the characters, we start taking out the
character one by one until we reach the bottom of the stack.

UNDO/REDO: It can also be used for performing


UNDO/REDO operations. For example, we have an editor in
which we write 'a', then 'b', and then 'c'; therefore, the text
written in an editor is abc. So, there are three states, a, ab, and
abc, which are stored in a stack. There would be two stacks in
which one stack shows UNDO state, and the other shows
REDO state.
If we want to perform UNDO operation, and want to achieve
'ab' state, then we implement pop operation.
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.

DFS(Depth First Search): This search is implemented on a


Graph, and Graph uses the stack data structure.

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.
•Expression conversion: Stack can also be used for
expression conversion. This is one of the most important
applications of stack.
•The list of the expression conversion is given below:
•Infix to prefix
•Infix to postfix
•Prefix to infix
• Prefix to postfix
•Postfix to infix
•Memory management:

•The stack manages the memory. The memory is assigned in


the contiguous memory blocks.

•The memory is known as stack memory as all the variables


are assigned in a function call stack memory.
•The memory size assigned to the program is known to the
compiler.
•When the function is created, all its variables are assigned in
the stack memory.
• When the function completed its execution, all the variables
assigned in the stack are released.
Adding an element onto the stack (push operation)

Adding an element into the top of the stack is referred to as


push operation.

Push operation involves following two steps.

Increment the variable Top so that it can now refer to the next
memory location.

Add element at the position of incremented top. This is


referred to as adding new element at the top of the stack.
Algorithm:(PUSH)
begin
if top = n then stack full
top = top + 1
stack (top) : = item;
end
Implementation of push algorithm in C language

void push (int val , int n) //n is size of the stack

{
if (top == n )
printf("\n Overflow");
else
{
top = top +1;
stack[top] = val;
}
}
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 decremented 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 :(POP)
begin
if top = 0 then stack empty;
item := stack(top);
top = top - 1;
end;
Time Complexity : o(1)
Implementation of POP algorithm using C language

int pop ()
{
if(top == -1)
{
printf ("Underflow");
return 0;
}
else
{
return stack[top - - ];
}
}
Infix expression: The expression of the form “a
operator b” (a + b) i.e., when an operator is in-
between every pair of operands.

Postfix expression: The expression of the form “a b


operator” (ab+) i.e., When every pair of operands is
followed by an operator.

Examples:
Input: A + B * C + D
Output: ABC*+D+
Why postfix representation of the expression?

The compiler scans the expression either from left to right or from right to
left.
Consider the expression: a + b * c + d

The compiler first scans the expression to evaluate the expression b * c,


then again scans the expression to add a to it.

The result is then added to d after another scan.

The repeated scanning makes it very inefficient. Infix expressions are


easily readable and solvable by humans whereas the computer cannot
differentiate the operators and parenthesis easily so, it is better to convert
the expression to postfix(or prefix) form before evaluation.

The corresponding expression in postfix form is abc*+d+. The postfix


expressions can be evaluated easily using a stack.
How to convert an Infix expression to a Postfix
expression?

To convert infix expression to postfix expression, use


the stack data structure.
Scan the infix expression from left to right.

Whenever we get an operand, add it to the postfix


expression and if we get an operator or parenthesis add
it to the stack by maintaining their precedence.
Below are the steps to implement the above idea:

1.Scan the infix expression from left to right.

2.If the scanned character is an operand, put it in the postfix expression.

3.Otherwise, do the following

 If the precedence and associativity of the scanned operator are greater


than the precedence and associativity of the operator in the stack [or the
stack is empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘
operator is right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘ are
left-associative].

 Check especially for a condition when the operator at the top of the stack
and the scanned operator both are ‘^‘. In this condition, the precedence of
the scanned operator is higher due to its right associativity. So it will be
pushed into the operator stack.
In all the other cases when the top of the operator stack
is the same as the scanned operator, then pop the
operator from the stack because of left associativity due
to which the scanned operator has less precedence.
 Else, Pop all the operators from the stack which are
greater than or equal to in precedence than that of the
scanned operator.
 After doing that Push the scanned operator to the stack.
(If you encounter parenthesis while popping then stop
there and push the scanned operator in the stack.)
4.If the scanned character is a ‘(‘, push it to the
stack.
5.If the scanned character is a ‘)’, pop the stack and
output it until a ‘(‘ is encountered, and discard both
the parenthesis.
6.Repeat steps 2-5 until the infix expression is
scanned.
7.Once the scanning is over, Pop the stack and add
the operators in the postfix expression until it is not
empty.
8.Finally, print the postfix expression.
Illustration:
Follow the below illustration for a better understanding

Consider the infix expression exp = “a+b*c+d”


and the infix expression is scanned using the iterator i, which is
initialized as i = 0.
1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this
in the postfix expression. Therefore, postfix = “a”.
2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the
stack. postfix = “a” and stack = {+}.

Push ‘+’ in the stack


3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the
postfix expression. postfix = “ab” and stack = {+}.

Add ‘b’ in the postfix


4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the
stack. postfix = “ab” and stack = {+, *}.

Push ‘*’ in the stack


5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the
postfix expression. postfix = “abc” and stack = {+, *}.

Add ‘c’ in the postfix


6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost
element of the stack has higher precedence. So pop until the stack
becomes empty or the top element has less precedence. ‘*’ is popped
and added in postfix. So postfix = “abc*” and stack = {+}.

Pop ‘*’ and add in postfix


Now top element is ‘+‘ that also doesn’t have less precedence. Pop
it. postfix = “abc*+”.

Pop ‘+’ and add it in postfix


Now stack is empty. So push ‘+’ in the stack. stack =
{+}.

Push ‘+’ in the stack


7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the
postfix expression. postfix = “abc*+d”.

Add ‘d’ in the postfix

Add ‘d’ in the postfix


Final Step: Now no element is left. So empty the stack and add it in
the postfix expression. postfix = “abc*+d+”.

Pop ‘+’ and add it in postfix


Given a string, reverse it using stack.
Example:
Input: str = “GeeksQuiz”
Output: ziuQskeeG
Input: str = “abc”
Output: cba

Approach:

The idea is to create an empty stack and push all the characters
from the string into it. Then pop each character one by one from
the stack and put them back into the input string starting from
the 0’th index. As we all know, stacks work on the principle of
first in, last out. After popping all the elements and placing them
back to string, the formed string would be reversed.
Convert the following Infix Notations into Postfix:

1.Input: A*B+C

2.Input: (A+B)*(C/D)

3.Input: A*(B*C+D*E)+F

4.Input: (A+B)*C+(D-E)/F+G
1. Output: AB*C+

2. Output: AB+CD/*

3. Output: ABC*DE*+*F+

4. Output: AB+C*DE-F/+G+
Convert the following Infix expression to
Postfix form using a stack

x + y * z + (p * q + r) * s,

Follow usual precedence rule and


assume that the expression is legal.
Follow the steps given below to reverse a string using stack.

Create an empty stack.

One by one push all characters of string to stack.

One by one pop all characters from stack and put them back
to string.
Evaluation of postfix expression

Algorithm

Scan the input string from left to right.

For each input symbol,

If it is a digit then, push it on to the stack.

If it is an operator then, pop out the top most two contents


from the stack and apply the operator on them.

Later on, push the result on to stack.

If the input symbol is ‘\0’, empty the stack.


What is Queue Data Structure?

A Queue is defined as a linear data structure that is open at both


ends and the operations are performed in First In First Out
(FIFO) order.

We define a queue to be a list in which all additions to the list


are made at one end, and all deletions from the list are made at
the other end.

The element which is first pushed into the order, the operation is
first performed on that.
•FIFO Principle of Queue:

•A Queue is like a line waiting to purchase tickets, where the first person
in line is the first person served. (i.e. First come first serve).

•Position of the entry in a queue ready to be served, that is, the first entry
that will be removed from the queue, is called the front of the
queue(sometimes, head of the queue),
•similarly, the position of the last entry in the queue, that is, the one most
recently added, is called the rear (or the tail) of the queue. See the b
Characteristics of Queue:

Queue can handle multiple data.

We can access both ends.

They are fast and flexible.


Difference between Stack and Queue Data Structures are as follows:
Stacks Queues
A queue is a data structure that stores a
A stack is a data structure that stores a
collection of elements, with operations
collection of elements, with operations
to enqueue (add) elements at the back
to push (add) and pop (remove)
of the queue, and dequeue (remove)
elements from the top of the stack.
elements from the front of the queue.
Stacks are based on the LIFO Queues are based on the FIFO
principle, i.e., the element inserted at principle, i.e., the element inserted at
the last, is the first element to come the first, is the first element to come
out of the list. out of the list.
Stacks are often used for tasks that Queues are often used for tasks that
require backtracking, such as parsing involve processing elements in a
expressions or implementing undo specific order, such as handling
functionality. requests or scheduling tasks.
Insertion and deletion in queues takes
Insertion and deletion in stacks takes place from the opposite ends of the
place only from one end of the list list. The insertion takes place at the
called the top. rear of the list and the deletion takes
place from the front of the list.
Insert operation is called push Insert operation is called enqueue
operation. operation.
Stacks are implemented using an array or Queues are implemented using an array or
linked list data structure. linked list data structure.

Delete operation is called dequeue


Delete operation is called pop operation.
operation.

In queues we maintain two pointers to


In stacks we maintain only one pointer to access the list. The front pointer always
access the list, called the top, which points to the first element inserted in the
always points to the last element present list and is still present, and the rear
in the list. pointer always points to the last inserted
element.

Stack is used in solving problems works Queue is used in solving problems having
on recursion. sequential processing.

Queues are often used in multithreaded


Stacks are often used for recursive
applications, where tasks are added to a
algorithms or for maintaining a history of
queue and executed by a pool of worker
function calls.
threads.
Queue is of three types – 1. Circular
Stack does not have any types. Queue 2. Priority queue 3. double-ended
queue.
Can be considered as a vertical collection Can be considered as a horizontal
visual. collection visual.
Examples of queue-based algorithms
Examples of stack-based languages
include Breadth-First Search (BFS) and
include PostScript and Forth.
printing a binary tree level-by-level.
Applications of queue:

Queue data structure is implemented in the hardware microinstructions


inside a CPU.
Queue structure is used in most operating systems.
Queues are widely used as waiting lists for a single shared
resource like printer, disk, CPU.
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.
Queues are used as buffers in most of the applications like
MP3 media player, CD player, etc.
Queue are used to maintain the play list in media players in
order to add and remove the songs from the play-list.
Queues are used in operating systems for handling interrupts.
Types of Queue

There are four different types of queue that are listed as follows -
Simple Queue or Linear Queue
In Linear Queue, an insertion takes place from one end while the deletion
occurs from another end. The end at which the insertion takes place is
known as the rear end, and the end at which the deletion takes place is
known as front end. It strictly follows the FIFO rule.

The major drawback of using a linear Queue is that insertion is done only
from the rear end. If the first three elements are deleted from the Queue, we
cannot insert more elements even though the space is available in a Linear
Queue. In this case, the linear Queue shows the overflow condition as the
rear is pointing to the last element of the Queue.
Circular Queue

In Circular Queue, all the nodes are represented as circular. It is similar to the linear Queue
except that the last element of the queue is connected to the first element. It is also known
as Ring Buffer, as all the ends are connected to another end. The representation of circular
queue is shown in the below image -

The drawback that occurs in a linear queue is overcome by using the circular queue. If the
empty space is available in a circular queue, the new element can be added in an empty
space by simply incrementing the value of rear. The main advantage of using the circular
queue is better memory utilization.
Priority Queue

It is a special type of queue in which the elements are arranged based on


the priority. It is a special type of queue data structure in which every
element has a priority associated with it. Suppose some elements occur
with the same priority, they will be arranged according to the FIFO
principle. The representation of priority queue is shown in the below image
Deque (or, Double Ended Queue)

In Deque or Double Ended Queue, insertion and deletion can be done from both
ends of the queue either from the front or rear. It means that we can insert and
delete elements from both front and rear ends of the queue. Deque can be used as
a palindrome checker means that if we read the string from both ends, then the
string would be the same.
Deque can be used both as stack and queue as it allows the insertion and deletion
operations on both ends. Deque can be considered as stack because stack follows
the LIFO (Last In First Out) principle in which insertion and deletion both can be
performed only from one end. And in deque, it is possible to perform both
insertion and deletion from one end, and Deque does not follow the FIFO principle.
The fundamental operations that can be performed on queue are listed
as follows

Enqueue: The Enqueue operation is used to insert the element at the


rear end of the queue. It returns void.

Dequeue: It performs the deletion from the front-end of the queue. It


also returns the element which has been removed from the front-end. It
returns an integer value.

Peek: This is the third operation that returns the element, which is
pointed by the front pointer in the queue but does not delete it.

Queue overflow (isfull): It shows the overflow condition when the


queue is completely full.

Queue underflow (isempty): It shows the underflow condition when the


Queue is empty, i.e., no elements are in the Queue.
Array representation of Queue

We can easily represent queue by using linear arrays. There are two
variables i.e. front and rear, that are implemented in the case of every
queue. Front and rear variables point to the position from where insertions
and deletions are performed in a queue. Initially, the value of front and
queue is -1 which represents an empty queue. Array representation of a
queue containing 5 elements along with the respective values of front and
rear, is shown in the following figure.
Insertion operation: enqueue()

The enqueue() is a data manipulation operation that is used


to insert elements into the stack. The following algorithm
describes the enqueue() operation in a simpler way.
Algorithm
1 − START
2 – Check if the queue is full.
3 − If the queue is full, produce overflow error and exit.
4 − If the queue is not full, increment rear pointer to point
the next empty space.
5 − Add data element to the queue location, where the rear
is pointing.
6 − return success.
7 – END
Deletion Operation: dequeue()

The dequeue() is a data manipulation operation that is used to


remove elements from the stack. The following algorithm
describes the dequeue() operation in a simpler way.

Algorithm
1 – START
2 − Check if the queue is empty.
3 − If the queue is empty, produce underflow error and exit.
4 − If the queue is not empty, access the data where front is
pointing.
5 − Increment front pointer to point to the next available data
element.
6 − Return success.
7 – END

You might also like