DS Unit-2 Final
DS Unit-2 Final
What is a Stack?
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. 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.
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.
o 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.
o 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.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o count(): It returns the total number of elements available in a stack.
o change(): It changes the element at the given position.
o display(): It prints all the elements available in the stack.
PUSH operation
POP operation
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.
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. Let’s see how each operation can be implemented on
the stack using array data structure.
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 refer 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 overflow when we try to insert an element into a completely filled stack therefore,
our main function must always avoid stack overflow condition.
Algorithm:
if (top == n )
printf("\n Overflow");
else
stack[top] = val;
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.
int pop ()
if(top == -1)
printf("Underflow");
return 0;
else
return stack[top - - ];
}
Visiting each element of the stack (Peek operation)
Peek operation involves returning the element which is present at the top of the stack without
deleting it. Underflow condition can occur if we try to return the top element in an already
empty stack.
int peek()
if (top == -1)
printf("Underflow");
return 0;
else
void show()
for (i=top;i>=0;i--)
printf("%d\n",stack[i]);
if(top == -1)
printf("Stack is empty");
} }
Linked list implementation of stack
Instead of using array, we can also use linked list to implement stack. Linked list allocates the
memory dynamically. However, time complexity in both the scenario is same for all the
operations i.e. push, pop and peek.
In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory. Each node contains a pointer to its immediate successor node in the stack. Stack is
said to be overflow if the space left in the memory heap is not enough to create a node.
The top most node in the stack always contains null in its address field. Lets discuss the way
in which, each operation is performed in linked list implementation of stack.
Adding a node to the stack is referred to as push operation. Pushing an element to a stack in
linked list implementation is different from that of an array implementation. In order to push
an element onto the stack, the following steps are involved.
void push ()
int val;
if(ptr == NULL)
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
ptr->val = val;
head=ptr;
else
ptr->val = val;
ptr->next = head;
head=ptr;
printf("Item pushed");
Deleting a node from the top of stack is referred to as pop operation. Deleting a node from
the linked list implementation of stack is different from that in the array implementation. In
order to pop an element from the stack, we need to follow the following steps :
1. Check for the underflow condition: The underflow condition occurs when we try to pop
from an already empty stack. The stack will be empty if the head pointer of the list points to
null.
2. Adjust the head pointer accordingly: In stack, the elements are popped only from one
end, therefore, the value stored in the head pointer must be deleted and the node must be
freed. The next node of the head node now becomes the head node.
void pop()
int item;
if (head == NULL)
printf("Underflow");
else
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
Displaying all the nodes of a stack needs traversing all the nodes of the linked list
organized in the form of stack. For this purpose, we need to follow the following
steps.
int i;
ptr=head;
if(ptr == NULL)
printf("Stack is empty\n");
else
while(ptr!=NULL)
printf("%d\n",ptr->val);
ptr = ptr->next;
Applications of Stack:
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the
processor’sstack.
5. During a function call the return address and arguments are pushed onto a
stack and on return they are popped off.
Transforming Infix Expressions into Postfix Expressions:
When the operator is written in between the operands, then it is known as infix notation.
In the algebraic expression, the order of the operator precedence is given in the below table:
Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
The operators that have the same precedence termed as operator associatively. If we go
from left to right, then it is known as left-associative. If we go from right to left, then it is
known as right-associative.
To evaluate the infix expression, we should know about the operator precedence rules, and
if the operators have the same precedence, then we should follow the associativity rules. The
use of parenthesis is very important in infix notation to control the order in which the
operation to be performed. Parenthesis improves the readability of the expression. An infix
expression is the most common way of writing expression, but it is not easy to parse and
evaluate the infix expression without ambiguity. So, mathematicians and logicians studied
this problem and discovered two other ways of writing expressions which are prefix and
postfix. Both expressions do not require any parenthesis and can be parsed without
ambiguity. It does not require operator precedence and associativity rules.
Postfix Expression
The postfix expression is an expression in which the operator is written after the operands.
For example, the postfix expression of infix notation ( 2+3) can be written as 23+.
K K
+ +
L + KL
- - K L+
M - K L+ M
* -* K L+ M
N -* KL+MN
+ + K L + M N*
K L + M N* -
( +( K L + M N *-
O +( KL+MN*-O
^ +(^ K L + M N* - O
P +(^ K L + M N* - O P
) + K L + M N* - O P ^
* +* K L + M N* - O P ^
W +* K L + M N* - O P ^ W
/ +/ K L + M N* - O P ^ W *
U +/ K L + M N* - O P ^W*U
/ +/ K L + M N* - O P ^W*U/
V +/ KL + MN*-OP^W*U/V
* +* KL+MN*-OP^W*U/V/
T +* KL+MN*-OP^W*U/V/T
+ + KL+MN*-OP^W*U/V/T*
KL+MN*-OP^W*U/V/T*+
Q + KL+MN*-OP^W*U/V/T*Q
KL+MN*-OP^W*U/V/T*+Q+
A+(B*C-(D/E^F)*G)*H
A+(B*C-(D/E^F)*G)*H A
A+(B*C-(D/E^F)*G)*H A +
A+(B*C-(D/E^F)*G)*H A +(
A+(B*C-(D/E^F)*G)*H AB +(
A+(B*C-(D/E^F)*G)*H AB +(*
A+(B*C-(D/E^F)*G)*H ABC*DEF^/G*- +
A+(B*C-(D/E^F)*G)*H ABC*DEF^/G*- +*
A+(B*C-(D/E^F)*G)*H ABC*DEF^/G*-H +*
A+(B*C-(D/E^F)*G)*H ABC*DEF^/G*-H*+
ANS: PQ+RS+*T/ABC+*+
6)
7. Input: A*B+C
Output: AB*C+
Input: (A+B)*(C/D)
Output: AB+CD/*
Input: A*(B*C+D*E)+F
Output: ABC*DE*+*F+
Input: (A+B)*C+(D-E)/F+G
Output: AB+C*DE-F/+G+
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.
3. For example, people waiting in line for a rail ticket form a queue.
Applications of Queue:
Types of Queue
There are four different types of queue that are listed as follows -
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.
The above figure shows the queue of characters forming the English word "HELLO". Since,
No deletion is performed in the queue till now, therefore the value of front remains -1 .
However, the value of rear increases by one every time an insertion is performed in the
queue. After inserting an element into the queue shown in the above figure, the queue will
look something like following. The value of rear will become 5 while the value of front
remains same.
After deleting an element, the value of front will increase from -1 to 0. however, the queue
will look something like following.
Algorithm to insert any element in a queue
Check if the queue is already full by comparing rear to max - 1. if so, then return an overflow
error.
If the item is to be inserted as the first element in the list, in that case set the value of front
and rear to 0 and insert the element at the rear end.
Otherwise keep increasing the value of rear and insert each element one by one having rear as
the index.
Algorithm
o Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
o Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
o Step 3: Set QUEUE[REAR] = NUM
o Step 4: EXIT
If, the value of front is -1 or value of front is greater than rear , write an underflow message
and exit.
Otherwise, keep increasing the value of front and return the item stored at the front end of the
queue at each time.
Algorithm
o Step 1: IF FRONT = -1 or FRONT > REAR
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
o Step 2: EXIT
Although, the technique of creating a queue is easy, but there are some drawbacks of using
this technique to implement a queue.
o Memory wastage: The space of the array, which is used to store queue elements, can
never be reused to store the elements of that queue because the elements can only be
inserted at front end and the value of front might be so high so that, all the space
before that, can never be filled.
One of the most common problem with array implementation is the size of the array which
requires to be declared in advance. Due to the fact that, the queue can be extended at runtime
depending upon the problem, the extension in the array size is a time taking process and
almost impossible to be performed at runtime since a lot of reallocations take place. Due to
this reason, we can declare the array large enough so that we can store queue elements as
enough as possible but the main problem with this declaration is that, most of the array slots
(nearly half) can never be reused. It will again lead to memory wastage.
Linked List implementation of Queue
The array implementation cannot be used for the large scale applications where the queues
are implemented. One of the alternatives of array implementation is linked list
implementation of queue.
The storage requirement of linked representation of a queue with n elements is o(n) while the
time requirement for operations is o(1).
In a linked queue, each node of the queue consists of two parts i.e. data part and the link part.
Each element of the queue points to its immediate next element in the memory.
In the linked queue, there are two pointers maintained in the memory i.e. front pointer and
rear pointer. The front pointer contains the address of the starting element of the queue while
the rear pointer contains the address of the last element of the queue.
Insertion and deletions are performed at rear and front end respectively. If front and rear both
are NULL, it indicates that the queue is empty.
There are two basic operations which can be implemented on the linked queues. The
operations are Insertion and Deletion.
Insert operation
The insert operation appends the queue by adding an element to the end of the queue. The
new element will be the last element of the queue.
Firstly, allocate the memory for the new node ptr by using the following statement.
There can be the two scenario of inserting this new node ptr into the linked queue.
In the first scenario, we insert element into an empty queue. In this case, the condition front
= NULL becomes true. Now, the new element will be added as the only element of the queue
and the next pointer of front and rear pointer both, will point to NULL.
In the second case, the queue contains more than one element. The condition front = NULL
becomes false. In this scenario, we need to update the end pointer rear so that the next pointer
of rear will point to the new node ptr. Since, this is a linked queue, hence we also need to
make the rear pointer point to the newly added node ptr. We also need to make the next
pointer of rear point to NULL.
Deletion
Deletion operation removes the element that is first inserted among all the queue elements.
Firstly, we need to check either the list is empty or not. The condition front == NULL
becomes true if the list is empty, in this case , we simply write underflow on the console and
make exit.
Otherwise, we will delete the element that is pointed by the pointer front. For this purpose,
copy the node pointed by the front pointer into the pointer ptr. Now, shift the front pointer,
point to its next node and free the node pointed by the node ptr. This is done by using the
following statements.
ptr = front;
front = front -> next;
free(ptr);
stacks Queues
1. A stack is a linear list of elements in whichthe 1. A Queue is a linerar list of elements in which
element may be inserted or deleted at one end. the elements are added at one end and
deletes the elements at another end.
2. In stacks, elements which are inserted last is 2. . In Queue the element which is inserted
the first element to be deleted. first is the element deleted first.
3. Stacks are called LIFO (Last In FirstOut)list 3. Queues are called FIFO (First In First
Out)list.
4. In stack elements are removed in reverseorder in
which thy are inserted. 4. In Queue elements are removed in the
same order in which thy are inserted.
5. suppose the elements a,b,c,d,e are
inserted in the stack, the deletion of 5. Suppose the elements a,b,c,d,e are inserted
elements will be e,d,c,b,a. in the Queue, the deletion of elements will be
in the same order in which thy are inserted.
6. In stack there is only one pointer to insertand
delete called “Top”. 6. In Queue there are two pointers one for
insertion called “Rear” and another for
7. Initially top=-1 indicates a stack is empty. deletion called “Front”.
9. To push an element into a stack, Top is 8. Queue is full represented by the condition
incremented by one Rear=Max-1.
10. To POP an element from stack,top is 9. To insert an element into Queue, Rear is
decremented by one. incremented by one.