You are on page 1of 58

S. J. P. N.

TRUST’S
HIRASUGAR INSTITUTE OF TECHNOLOGY, NIDASOSHI
Accredited at 'A' Grade by NAAC
Programmes Accredited by NBA: CSE, ECE, EEE & ME.

Department of Computer Science & Engineering

GATE-2021
Data Structures

Prof. S. V. Manjaragi
Asst. Prof. , Dept. of Computer Science & Engg.,
Hirasugar Institute of Technology, Nidasoshi
Contents
• What is Data Structure?
• Types of Data Structures
• Stack with sample examples
• Queue with sample examples
• Linked List with Sample examples

12/15/2022 2
What is Data structure?
Data Structure is a way of collecting and
organizing data in such a way that we can
perform operations on these data in an
effective way. 

12/15/2022 3
Types of Data Structures

12/15/2022 4
Stack
• Stack is a linear data structure which follows a
particular order in which the operations are
performed. The order may be LIFO(Last In First Out)
or FILO(First In Last Out).
• Basic operations 
– Push
– Pop
– Peek or Top
– isEmpty

12/15/2022 5
Application of stack
• Balancing of symbols
• Infix to Postfix /Prefix conversion
• Evaluation of Postfix expression
• Redo-undo features at many places like editors,
photoshop.
• Forward and backward feature in web browsers
• Used in many algorithms like Tower of Hanoi, tree
traversals, stock span problem, histogram problem.
• Other applications can be Backtracking,  N queen
problem and sudoku solver
12/15/2022 6
Implementation of Stack
• Using array
• Using linked list
• Implement two stacks in an array
Create a data structure twoStacks that represents two stacks.
Implementation of twoStacks should use only one array, i.e., both stacks
should use the same array for storing elements. Following functions
must be supported by twoStacks.
push1(int x) –> pushes x to first stack
push2(int x) –> pushes x to second stack
pop1() –> pops an element from first stack and return the popped
element
pop2() –> pops an element from second stack and return the popped
element

12/15/2022 7
Check for balanced parentheses in an expression

Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
    a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push

it to stack.
    b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop
from stack and if the popped character is the matching starting bracket
then fine else parenthesis are not balanced.

3) After complete traversal, if there is some starting bracket left in stack then
“not balanced”

12/15/2022 8
Infix to postfix conversion
• Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the
precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the
scanned operator is less-equal to the precedence of the operator residing
on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an
‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.

12/15/2022 9
Evaluation of Postfix Expression
(1) Create a stack to store operands (or values).
(2) Scan the given expression and do following for
every scanned element.
a) If the element is a number, push it into the stack
b) If the element is a operator, pop operands for
the operator from stack. Evaluate the operator and
push the result back to the stack
(3) When the expression is ended, the number in the
stack is the final answer

12/15/2022 10
Q1: Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to
do processing.
void fun(int n)
{
    Stack S;  // Say it creates an empty stack S
    while (n > 0)
    {
      // This line pushes the value of n%2 to stack S
      push(&S, n%2);
       n = n/2;
    }
     // Run while Stack S is not empty
    while (!isEmpty(&S))
      printf("%d ", pop(&S)); // pop an element from S and print it
}
What does the above function do in general?

A. Prints binary representation of n in reverse order


B. Prints binary representation of n
C. Prints the value of Logn in reverse order
D. Prints the value of Logn

ANS: B

12/15/2022 12
Q2: Which one of the following is an application of Stack Data
Structure?
A. Managing function calls
B. The stock span problem
C. Arithmetic expression evaluation
D. All of the above

ANS: D

12/15/2022 13
Q3: Which of the following is true about linked list
implementation of stack?
A. In push operation, if new nodes are inserted at the beginning
of linked list, then in pop operation, nodes must be removed
from other end.
B. In push operation, if new nodes are inserted at the end, then
in pop operation, nodes must be removed from the
beginning.
C. Both of the above
D. None of the above

ANS: D

12/15/2022 14
Q4: Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a
sequence of parentheses is balanced:
declare a character stack
while ( more input is available)
{
   read a character
   if ( the character is a '(' )
      push it on the stack
   else if ( the character is a ')' and the stack is not empty )
      pop a character off the stack
   else
      print "unbalanced" and exit
 }
 print "balanced“

Which of these unbalanced sequences does the above code think is balanced? 
A. ((())
B. ())(()
C. (()()))
D. (()))()

ANS: A

12/15/2022 15
Q5: The following postfix expression with single digit operands is evaluated using a
stack:
823^/23*+51*-
Note that ^ is the exponentiation operator. The top two elements of the stack
after the first * is evaluated are:
A. 6, 1
B. 5, 7
C. 3, 2
D. 1, 5

ANS: A

12/15/2022 16
Q6: A single array A[1..MAXSIZE] is used to implement two stacks. The two stacks
grow from opposite ends of the array. Variables top1 and top2 (topl< top 2) point
to the location of the topmost element in each of the stacks. If the space is to be
used efficiently, the condition for “stack full” is

Which of these unbalanced sequences does the above code think is balanced? 
A. (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)
B. top1 + top2 = MAXSIZE
C. (top1= MAXSIZE/2) or (top2 = MAXSIZE)
D. top1= top2 -1

ANS: D

12/15/2022 17
Q7: Assume that the operators +, -, × are left associative and ^ is right
associative. The order of precedence (from highest to lowest) is ^, x , +, -.
The postfix expression corresponding to the infix expression a + b × c - d ^
e ^ f is
A. abc × + def ^ ^ -
B. abc × + de ^ f ^ -
C. ab + c × d - e ^ f ^
D. - + a × bc ^ ^ def

ANS: A

12/15/2022 18
Q9: Consider the following C program:

What is the output of the program for the following input ? 5 2 * 3 3 2 + * +

A. 15
B. 25
C. 30
D. 150

ANS: B

12/15/2022 20
Other problems on Stack
• Implement Queue using Stacks
• Implement Stack using Queues
• How to efficiently implement k stacks in a single array?
• The Stock Span Problem
• The Celebrity Problem
• Iterative Tower of Hanoi
• Reverse a stack using recursion
• Sort a stack using recursion
• Sort a stack using a temporary stack
12/15/2022 21
Queue
• Queue is a linear structure which follows a particular
order in which the operations are performed. The
order is First In First Out (FIFO). 
• Basic operations 
– Enqueue
– Dequeue
– Front
– Rear

12/15/2022 22
Application of Queue
• When a resource is shared among multiple
consumers. Examples include CPU scheduling,
Disk Scheduling.
• When data is transferred asynchronously (data
not necessarily received at same rate as sent)
between two processes. Examples include IO
Buffers, pipes, file IO, etc.
• Breadth First Traversal 

12/15/2022 23
Priority Queue 
• Priority Queue is an extension of queue with following
properties.
1) Every item has a priority associated with it.
2) An element with high priority is dequeued before an
element with low priority.
3) If two elements have the same priority, they are
served according to their order in the queue.
• Applications
– CPU Scheduling
– Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s
Minimum Spanning Tree, 
12/15/2022 24
Deque

• Deque or Double Ended Queue is a


generalized version of Queue data
structure that allows insert and delete at both
ends.
• Applications
– Deque supports both stack and queue operations,
it can be used as both
– Graph algorithms like Dijkstra’s shortest path
algorithm, Prim’s Minimum Spanning Tree, 
12/15/2022 25
Circular Queue
• Circular Queue is a linear data structure in
which the operations are performed based on
FIFO (First In First Out) principle and the last
position is connected back to the first position
to make a circle. It is also called ‘Ring Buffer’.

12/15/2022 26
Q1: Following is C like pseudo code of a function that takes a Queue as an argument, and uses a stack S to do processing.

void fun(Queue *Q)


{
    Stack S;  // Say it creates an empty stack S
 
    // Run while Q is not empty
    while (!isEmpty(Q))
    {
        // deQueue an item from Q and push the dequeued item to S
        push(&S, deQueue(Q));
    }
 
    // Run while Stack S is not empty
    while (!isEmpty(&S))
    {
      // Pop an item from S and enqueue the poppped item to Q
      enQueue(Q, pop(&S));
    }
}

 What does the above function do in general?


A. Removes the last from Q
B. Keeps the Q same as it was before the call
C. Makes Q empty
D. Reverses the Q

ANS: D

12/15/2022 27
Q2: Which one of the following is an application of Queue Data Structure?
A. When a resource is shared among multiple consumers
B. When data is transferred asynchronously (data not necessarily received at same
rate as sent) between two processes
C. Load Balancing
D. All of the above

ANS: D

12/15/2022 28
Q3: How many stacks are needed to implement a queue. Consider the
situation where no other data structure like arrays, linked list is available
to you.
A. 1
B. 2
C. 3
D. 4
ANS: B

12/15/2022 29
Q4: A priority queue can efficiently implemented using which of the
following data structures? Assume that the number of insert and peek
(operation to see the current highest priority item) and extraction (remove
the highest priority item) operations are almost same.
A. Array
B. Linked List
C. Heap Data Structures like Binary Heap, Fibonacci Heap
D. None of the above
ANS: C

12/15/2022 30
Q5: Which of the following is true about linked list implementation of
queue?
A. In push operation, if new nodes are inserted at the beginning of linked list,
then in pop operation, nodes must be removed from end.
B. In push operation, if new nodes are inserted at the end, then in pop
operation, nodes must be removed from the beginning.
C. Both of the above
D. None of the above
ANS: C

12/15/2022 31
Q6: Suppose a circular queue of capacity (n – 1) elements is implemented
with an array of n elements. Assume that the insertion and deletion
operation are carried out using REAR and FRONT as array index variables,
respectively. Initially, REAR = FRONT = 0. The conditions to detect queue
full and queue empty are
A. Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT
B. Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR
C. Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT
D. Full: (FRONT+1) mod n == REAR, empty: REAR == FRONT
ANS: A

12/15/2022 32
Q7: Consider the following pseudo code. Assume that IntQueue is an integer
queue. What does the function fun do?

A. Prints numbers from 0 to n-1


B. Prints numbers from n-1 to 0
C. Prints first n Fibonacci numbers
D. Prints first n Fibonacci numbers in reverse order
ANS: C
12/15/2022 33
Q8: Consider the following operation along with Enqueue and Dequeue operations on
queues, where k is a global parameter.

What is the worst case time complexity of a sequence of n MultiDequeue()operations on an


initially empty queue?

A. O(n)
B. O(n+k)
C. O(nk)
D. None of these

ANS: A

12/15/2022 34
Q9: A queue is implemented using an array such that ENQUEUE and
DEQUEUE operations are performed efficiently. Which one of the
following statements is CORRECT (n refers to the number of items in the
queue)?
A. Both operations can be performed in O(1) time
B. At most one operation can be performed in O(1) time but the worst case
time for the other operation will be Ω(n)
C. The worst case time complexity for both operations will be Ω(n)
D. Worst case time complexity for both operations will be Ω(log n)

ANS: A
We can use circular array to implement both in O(1) time

12/15/2022 35
Q10: Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the
element at the head of the queue Q without removing it from Q. Similarly Top(S) returns the element
at the top of S without removing it from S. Consider the algorithm given below.

The maximum possible number of iterations of the while loop in the algorithm is______
A. 16
B. 32
C. 256
D. 64

ANS: C
The worst case happens when the queue is sorted in decreasing order. In worst case, loop runs n*n times.

12/15/2022 36
Other problems on Queue
• Breadth First Traversal or BFS for a Graph
• Level Order Tree Traversal
• Program for Page Replacement Algorithms 
• Reversing a Queue
• Reversing the first K elements of a Queue
• LRU Cache Implementation
• How to efficiently implement k Queues in a single array?
• Implement a stack using single queue
• Implementation of Deque using circular array

12/15/2022 37
LinkedList
• Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements
are not stored at contiguous location; the elements are linked using pointers.

• Why Linked List?


• Advantages over arrays
– Dynamic size
– Ease of insertion/deletion
• Drawbacks:
– Random access is not allowed.
– Extra memory space for a pointer is required with each element of the list.
• Representation in C
• Types of Linked List

12/15/2022 38
• Linked List Insertion
LinkedList Operations
• Linked List Deletion (Deleting a given key)
• Linked List Deletion (Deleting a key at given position)
• Search an element in a Linked List (Iterative and Recursive)
• Swap nodes in a linked list without swapping data
• Write a function to get Nth node in a Linked List
• Print the middle of a given linked list
• Nth node from the end of a Linked List
• Write a function to delete a Linked List
• Write a function that counts the number of times a given int occurs in a Linked List
• Reverse a linked list
• Detect loop in a linked list
• Merge two sorted linked lists
• Function to check if a singly linked list is palindrome
• Intersection point of two Linked Lists.
• Remove duplicates from a sorted linked list
• Remove duplicates from an unsorted linked list
• Pairwise swap elements of a given linked list
• Move last element to front of a given Linked List
• Intersection of two Sorted Linked Lists
• Delete alternate nodes of a Linked List
• Identical Linked Lists
• Merge Sort for Linked Lists
• Reverse alternate K nodes in a Singly Linked List
• Delete nodes which have a greater value on right side
• Segregate even and odd nodes in a Linked List
• Add two numbers represented by linked lists
• Rotate a Linked List
• Delete N nodes after M nodes of a linked list
• Compare two strings represented as linked lists
• Rearrange a linked list such that all even and odd positioned nodes are together
• Merge two sorted linked lists such that merged list is in reverse order
• Delete last occurrence of an item from linked list
• Delete a Linked List node at a given position
• Delete middle of linked list
• Decimal Equivalent of Binary Linked List
• Remove all occurrences of duplicates from a sorted Linked List

12/15/2022 39
Q1: What does the following function do for a given Linked List with first node
as head?

A. Prints all nodes of linked lists


B. Prints all nodes of linked list in reverse order
C. Prints alternate nodes of Linked List
D. Prints alternate nodes in reverse order
ANS: B
12/15/2022 40
Q2: Which of the following points is/are true about Linked List
data structure when it is compared with array

A. Arrays have better cache locality that can make them better in
terms of performance
B. It is easy to insert and delete elements in Linked List
C. Random access is not allowed in a typical implementation of
Linked Lists
D. The size of array has to be pre-decided, linked lists can change
their size any time.
E. All of the above

ANS: E

12/15/2022 41
Q3: Consider the following function that takes reference to head of a Doubly Linked List as parameter.
Assume that a node of doubly linked list has previous pointer as prev and next pointer as next.

Assume that reference of head of following doubly linked list is passed to above function
1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6. What should be the modified linked list after the function call?
A. 2 <--> 1 <--> 4 <--> 3 <--> 6 <-->5
B. 5 <--> 4 <--> 3 <--> 2 <--> 1 <-->6
C. 6 <--> 5 <--> 4 <--> 3 <--> 2 <--> 1
D. 6 <--> 5 <--> 4 <--> 3 <--> 1 <--> 2

ANS: C

12/15/2022 42
Q4: What is the output of following function for start pointing to first node of
following linked list? 1->2->3->4->5->6

A. 1 4 6 6 4 1
B. 1 3 5 1 3 5
C. 1 2 3 5
D. 1 3 5 5 3 1

ANS: D
fun() prints alternate nodes of the given Linked List, first from head to end, and then
from end to head. If Linked List has even number of nodes, then skips the last
node.

12/15/2022 43
Q5: In the worst case, the number of comparisons needed to
search a singly linked list of length n for a given element is
A. log 2 n
B. n/2
C. log 2 n – 1
D. n.

ANS: D

12/15/2022 44
Q6: Consider the function f defined below.

For a given linked list p, the function f returns 1 if and only if 
A. the list is empty or has exactly one element
B. the elements in the list are sorted in non-decreasing order of data value
C. the elements in the list are sorted in non-increasing order of data value
D. not all elements in the list have the same data value.

ANS: B

12/15/2022 45
Trees
• A tree is a collection of nodes. The collection
can be empty.Otherwise, a tree consists of a
distinguished node r, called the root, and zero
or more (sub)trees T1, T2, . . . , Tk, each of whose
roots are connected by a directed edge to r.
• The root of each subtree is said to be a child of
r, and r is the parent of each subtree root.

12/15/2022 46
Recursive defination
• From the recursive definition, we find that a tree is a
collection of n nodes, one of which is the root, and n
- 1 edges.
• That there are n - 1 edges follows from the fact that
each edge connects some node to its parent, and
every node except the root has one parent
• Nodes with no children are known as leaves
• Nodes with the same parent are siblings
• Grandparent and grandchild relations can be defined

12/15/2022 47
12/15/2022 48
• A path from node n1 to nk is defined as a sequence of
nodes n1, n2, . . . , nk such that ni is the parent of ni+1 for
1< i < k.
• The length of this path is the number of edges on the
path, namely k -1.
• There is a path of length zero from every node to itself.
• Notice that in a tree there is exactly one path from the
root to each node.
• For any node ni, the depth of ni is the length of the
unique path from the root to ni.
• Thus, the root is at depth 0.

12/15/2022 49
• The height of ni is the longest path from ni to a
leaf.
• Thus all leaves are at height 0.
• The height of a tree is equal to the height of
the root.
• The depth of a tree is equal to the depth of
the deepest leaf; this is always equal to the
height of the tree.
• If there is a path from n1 to n2, then n1 is an
ancestor of n2 and n2 is a descendant of n1.

12/15/2022 50
Tree Traversals
• Inorder
• Preorder
• Postorder

12/15/2022 51
Binary Trees
• A binary tree is a tree in which no node can have
more than two children.

• shows that a binary tree consists of a root and two


subtrees, Tl and Tr, both of which could possibly be
empty.
• A property of a binary tree that is sometimes
important is that the depth of an average binary tree
is considerably smaller than n.
• An analysis shows that the average depth is
12/15/2022 52
• the binary search tree, the average value of
the depth is O(log n).
• the depth can be as large as n -1

12/15/2022 53
Expression Trees

• Inorder traversal will produce the infix expression


• Postorder traversal generates the postfix expression
• Preorder traversal generates the prefix expression

12/15/2022 54
Constructing an Expression Tree
• The method we describe strongly resembles the postfix
evaluation algorithm
• We read our expression one symbol at a time.
• If the symbol is an operand, we create a one-node tree
and push a pointer to it onto a stack.
• If the symbol is an operator, we pop pointers to two trees
T1 and T2 from the stack (T1 is popped first) and form a
new tree whose root is the operator and whose left and
right children point to T2 and T1 respectively.
• A pointer to this new tree is then pushed onto the stack.

12/15/2022 55
Next, a '+' is read, so two pointers to trees are popped, a new tree is formed, and a
pointer to it is pushed onto the stack.*

12/15/2022 56
12/15/2022 57
12/15/2022 58
The Search Tree ADT-Binary Search Trees

• Operations:
– Find
– Find_min and find_max
– Insert
– Delete
– we expect that all of the operations should take O(log n) time

12/15/2022 59
Thank You

12/15/2022 60

You might also like