0% found this document useful (0 votes)
2 views

Data Structure

The document provides an overview of various data structures, including Circular Linked Lists, Doubly Linked Lists, Stacks, Binary Trees, Priority Queues, and AVL Trees. It explains their characteristics, advantages, and operations, along with traversal methods for trees and search algorithms for graphs. Additionally, it covers concepts like Abstract Data Types, Inheritance, and Tournament Trees, highlighting their applications and significance in programming.

Uploaded by

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

Data Structure

The document provides an overview of various data structures, including Circular Linked Lists, Doubly Linked Lists, Stacks, Binary Trees, Priority Queues, and AVL Trees. It explains their characteristics, advantages, and operations, along with traversal methods for trees and search algorithms for graphs. Additionally, it covers concepts like Abstract Data Types, Inheritance, and Tournament Trees, highlighting their applications and significance in programming.

Uploaded by

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

Data Structure

Q1. What is Circular Linked List?


Ans. What is a Circular Linked List?
A Circular Linked List (CLL) is a special type of linked list where the last node points back to the first
node, forming a circle.
This means there is no NULL at the end of the list as in singly or doubly linked lists.
Key Features:
 Can be singly or doubly linked.
 Can be traversed from any node.
 Useful in applications requiring continuous cycling or looping.
Advantages:
1. Efficient for round-robin scheduling.
2. No need to reset pointer to the head after reaching the end.
3. Supports continuous traversal in loops

Q2. What are the problems with singly linked list that are overcome by doubly linked list? Explain how a
node can be inserted in a doubly linked list.

Problems with Singly Linked List Overcome by Doubly Linked List


A Singly Linked List (SLL) stores only one pointer (next), which leads to several limitations:
Problems in SLL:
1. Only Forward Traversal: Cannot move backward.
2. Difficult Deletion: To delete a node, the previous node must be tracked.
3. Insertion is Limited: Inserting before a node is tough.
4. No Efficient Backtracking: Cannot reverse-traverse the list.

How Doubly Linked List (DLL) Solves These Problems:


A Doubly Linked List has two pointers in each node:
 One pointing to the next node.
 One pointing to the previous node.
This allows bidirectional traversal, and makes insertion and deletion easier.

Insertion in Doubly Linked List (Between Two Nodes)


Let’s say we want to insert a new node C between two existing nodes A and B.
Steps:
1. Create new node C.
2. Set C.prev = A
3. Set C.next = B
4. Set A.next = C
5. Set B.prev = C

Diagram:
Before Insertion:
[A] <-> [B]

After Inserting C:
[A] <-> [C] <-> [B]
Q3. b) Write short notes on following:
i) Linked List representations
ii) Indirect addressing

Ans i) Linked List Representations


A Linked List is a linear data structure where elements (called nodes) are connected using pointers.
Each node typically has two parts:
1. Data – stores the actual value.
2. Pointer – holds the address of the next node.
Linked Lists can be of various types:
 Singly Linked List: One pointer to next node.
 Doubly Linked List: Two pointers – one to next and one to previous node.
 Circular Linked List: Last node points back to the first node.

Memory Representation:
In memory, nodes are not stored in contiguous locations. Instead, they are scattered, and pointers are used to
maintain the sequence.
Diagram (Singly Linked List):
[Data | Next] → [Data | Next] → [Data | NULL]
This dynamic memory allocation and flexibility make linked lists useful in implementing stacks, queues,
graphs, etc.

ii) Indirect Addressing


Indirect Addressing is a memory addressing technique where the address of the data is not directly given,
but stored in another location (like a register or memory cell), which is then accessed to get the actual data.

Key Points:
 Offers flexibility in accessing data.
 Common in pointer-based programming (e.g., C/C++).
 Widely used in arrays, linked lists, trees, and dynamic structures.
 Enables dynamic memory usage and complex data management.

Example:
If register R contains address 500, and memory at address 500 has value 42,
then using indirect addressing, we access value 42 indirectly through address 500.

Diagram:
Instruction → [Address 500] → [Memory = 42]
Indirect addressing is crucial in linked lists, function pointers, and memory management in operating
systems.
Q.3 a) Write short notes on following:
i) Abstract Data Type
ii) Derived classes and inheritance

Ans. i) Abstract Data Type (ADT)


An Abstract Data Type (ADT) is a mathematical model for a certain class of data structures that defines
the type of data stored, operations allowed, and the behavior of these operations, without specifying
implementation.
Key Characteristics:
 Abstraction: Hides internal structure, shows only what the object does.
 Encapsulation: Data + operations bundled together.
 Modularity: Independent of implementation, so implementation can change without affecting users.
Examples:
 Stack ADT: Operations like push(), pop(), and peek().
 Queue ADT: Operations like enqueue(), dequeue().
 List ADT: Operations like insert(), delete(), traverse().
Why ADTs are important?
 Helps in breaking down complex problems.
 Ensures that only intended operations are allowed.
 Increases reusability and flexibility.
Diagram – Stack as ADT:
Top → [40]
[30]
[20]
[10]
Operations: push(), pop(), peek()

ii) Derived Classes and Inheritance


Inheritance is a feature of Object-Oriented Programming (OOP) that allows a class to inherit the
properties and behavior (methods) of another class.
 Base Class: The class whose properties are inherited.
 Derived Class: The class that inherits those properties.
Types of Inheritance:
1. Single Inheritance: One base, one derived class.
2. Multilevel Inheritance: Inheritance in a chain.
3. Multiple Inheritance: One class inherits from more than one base class.
4. Hierarchical Inheritance: One base class has multiple derived classes.
Advantages:
 Code reusability: Common code need not be rewritten.
 Extensibility: Easy to add new features.
 Polymorphism: Same function name works differently in derived classes.
Example:
If a base class Animal has a function speak(), the derived class Dog can use or override this function.
Diagram:
[Class Animal]
|
[Class Dog inherits Animal]
Inheritance makes programs modular, reduces redundancy, and supports real-world modeling using class
hierarchies.

Q4. What is a Stack Data Structure? Write procedures for significant operations. Explain Stack
Overflow and Underflow.

STACK DATA STRUCTURE


A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. This means the last
element inserted into the stack is the first one to be removed.

Main Operations on Stack:


1. Push – Add an element to the top of the stack.
2. Pop – Remove the top element from the stack.
3. Peek/Top – View the element at the top without removing it.
4. isEmpty – Check if the stack has no elements.
5. isFull – Check if the stack is full (for fixed size stacks).

Stack Representation (Array-based):


Index → 0 1 2 3 4
[10][20][30][40][50] ← Top

If Top = 4, Stack is full (in 0-based index)

PROCEDURE FOR PUSH OPERATION:


Procedure PUSH(stack, item)
if TOP == MAX - 1
Print "Stack Overflow"
else
TOP ← TOP + 1
stack[TOP] ← item
PROCEDURE FOR POP OPERATION:
Procedure POP(stack)
if TOP == -1
Print "Stack Underflow"
else
item ← stack[TOP]
TOP ← TOP - 1
return item

STACK OVERFLOW
 Happens when you try to push an element into a full stack.
 Example:
o Stack size = 5

o Already contains 5 elements

o A 6th push will cause overflow.

Result: Memory can’t store the extra element. Program may crash or give error.

STACK UNDERFLOW
 Happens when you try to pop from an empty stack.
 Example:
o Stack is empty (TOP = -1)

o Pop operation is attempted

Result: Invalid operation. No data to remove. May cause crash or error.

APPLICATIONS OF STACK:
 Expression evaluation (postfix/infix).
 Undo operations in editors.
 Function call management (call stack).
 Backtracking problems (maze, recursion).

Diagram:
Stack (Top to Bottom)
[40] ← Top
[30]
[20]
[10]

Push(50):
[50] ← Top
[40]
...

Pop():
Removes [50], new top is [40]

Q5. What is Binary Tree traversal? Explain various methods of tree traversals.

Ans. Binary Tree Traversal


Binary Tree Traversal is the process of visiting each node in a binary tree exactly once in a systematic way.
Since trees are hierarchical structures (not linear like arrays), we need specific traversal techniques.
There are mainly two types of traversals:
1. Depth-First Traversal (DFT)
2. Breadth-First Traversal (BFT)

1. Depth-First Traversal (DFT)


In DFT, we go deep in the tree structure before backtracking. It is further classified into:
a) Inorder Traversal (Left, Root, Right)
 Traverse left subtree
 Visit the root
 Traverse right subtree
Example:
[A]
/ \
[B] [C]
/\
[D] [E]

Inorder: D → B → E → A → C

b) Preorder Traversal (Root, Left, Right)


 Visit the root
 Traverse left subtree
 Traverse right subtree
Example:
Preorder: A → B → D → E → C

c) Postorder Traversal (Left, Right, Root)


 Traverse left subtree
 Traverse right subtree
 Visit the root
Example:
Postorder: D → E → B → C → A

2. Breadth-First Traversal (Level Order)


In Level Order Traversal, we visit nodes level by level from top to bottom and left to right at each level. This
traversal uses a Queue.
Example:
Level Order: A → B → C → D → E

Diagram of Binary Tree:


[A]
/ \
[B] [C]
/\
[D] [E]
Summary Table:

Traversal Type Order Visited Usage Example

Inorder Left → Root → Right Binary Search Trees (BST)

Preorder Root → Left → Right Expression trees, copying

Postorder Left → Right → Root Deleting tree, postfix expr.

Level Order Top to Bottom, Left to Right Finding height or BFS

Applications:
 Inorder: Retrieves values in sorted order (for BSTs).
 Preorder: Used for copying a tree.
 Postorder: Used to delete a tree or evaluate postfix expressions.
 Level Order: Used in Breadth-First Search.
Q6. Write short notes on following:
i) Priority Queues
ii) Tournament Trees

i) Priority Queues
A Priority Queue is an abstract data structure that supports the operations of a queue with an added feature:
each element has a priority associated with it. Elements are dequeued in order of their priority, with the
element having the highest priority being dequeued first. If two elements have the same priority, they are
dequeued in the order they were added (this behavior can vary depending on the implementation).
Operations:
1. Insert: Add an element to the queue with a given priority.
2. Remove: Remove the element with the highest priority.
3. Peek: View the element with the highest priority without removing it.
Types of Priority Queues:
 Max Priority Queue: The element with the largest value is dequeued first.
 Min Priority Queue: The element with the smallest value is dequeued first.
Implementation:
Priority queues can be implemented using:
 Array/Linked List: Simple but inefficient for large datasets (O(n) for insertion and removal).
 Binary Heap: More efficient, where insertion and removal both take O(log n) time.
 Fibonacci Heap: Provides even better time complexity for certain operations like decrease-key.
ii) Tournament Trees
A Tournament Tree is a type of binary tree used to find the winner in a series of matches, where each match
involves two players, and the winner advances to the next level. It is a specialized data structure for
problems such as finding the k-th largest element in an array or efficiently implementing sorting algorithms.
In a tournament tree:
 Each leaf node represents a player or an element.
 Each internal node represents a match, where the winner is the element with the higher value.
 The root node holds the winner of the tournament (the maximum or minimum element, depending on
the problem's requirements).
Applications:
 Selection algorithms: Find the k-th largest element in an array.
 Sorting algorithms: Used in tournament sort for comparison-based sorting.
 Game theory: Simulate knockout rounds of tournaments.
Complexity:
 Build Tournament Tree: O(n) time.
 Find Winner (Root): O(1) time.
 Update (after match results): O(log n) time.

Diagram:
(Root)
/ \
(Match) (Match)
/ \ / \
(Leaf) (Leaf)(Leaf)(Leaf)
In this example, each match node compares the winners of its two child nodes and passes the winner up to
its parent, ultimately determining the overall winner at the root.
Q7. Write short notes on following:
i) AVL Trees
ii) Node structure in B-Tree
Ans. i) AVL Trees

An AVL Tree is a type of self-balancing binary search tree (BST) where the difference in height
(balance factor) between the left and right subtrees of any node is at most 1.

Key Features:
 Maintains O(log n) time complexity for insertion, deletion, and search operations.

Balance Factor:

Balance Factor=Height of Left Subtree−Height of Right Subtree\text{Balance Factor} = \text{Height of Left


Subtree} - \text{Height of Right Subtree}

 For AVL Tree, balance factor must be -1, 0, or +1 for all nodes.

Rotations to Balance:

1. Left-Left (LL) Rotation


2. Right-Right (RR) Rotation
3. Left-Right (LR) Rotation
4. Right-Left (RL) Rotation

These rotations are used to restore balance after insertion or deletion.

Diagram:

Before LL Rotation:

30
/
20
/
10

After LL Rotation:

20
/ \
10 30

ii) Node Structure in B-Tree

A B-Tree is a self-balancing multi-way search tree used primarily in databases and file systems for
efficiently handling large volumes of data stored on disks.

Node Structure:

Each node in a B-Tree contains:

 Keys: A sorted list of keys (values).


 Pointers: A list of child pointers (subtrees).
 Number of keys: A node with n keys has n + 1 children.

Properties:

Every internal node (except root) has at least ⌈m/2⌉ children.


1. Every node can have at most m children, where m is the order of the B-Tree.
2.
3. Keys within a node are sorted in ascending order.
4. All leaves appear at the same level (height-balanced).
5. The root has at least two children unless it is a leaf.
Example Diagram (Order 3 B-Tree):

[20]
/ \
[10] [30, 40]

Here:

 The root has 1 key (20) and 2 children.


 The left child has key 10, the right child has keys 30 and 40.

B-Trees are optimal for disk-based storage systems due to their low height and high branching factor.

Q8. Explain different graph search methods with an example.


Ans. Graph Search Methods
Graph search methods are algorithms used to traverse or search a graph's nodes (vertices) and edges in a
systematic way. The two most common graph search algorithms are:

1. Breadth-First Search (BFS)


Definition:
BFS explores the graph level by level, visiting all neighbors of a node before moving to the next level of
nodes.
Steps:
1. Start from a selected node (source).
2. Visit all its adjacent (neighboring) nodes.
3. Use a queue to keep track of the nodes to be visited.
4. Repeat until all nodes are visited.
Example:
Consider the graph:
A
/\
B C
/ \
D E
BFS Traversal starting from A:
→A→B→C→D→E
Diagram of BFS traversal:
Level 0: A
Level 1: B, C
Level 2: D, E

2. Depth-First Search (DFS)


Definition:
DFS explores as far as possible along one branch before backtracking. It goes deep into the graph before
exploring other branches.
Steps:
1. Start from a selected node (source).
2. Visit a neighbor, then a neighbor of that neighbor, and so on.
3. Use a stack (either explicit or recursion) to keep track of nodes.
4. Backtrack when no unvisited neighbors are left.
Example:
Using the same graph:
A
/\
B C
/ \
D E
DFS Traversal starting from A:
→A→B→D→C→E
Diagram of DFS traversal path:
Start at A
→ Go to B
→ Go to D (no more neighbors)
→ Backtrack to B → A
→ Go to C
→ Go to E

Comparison Table:

Feature BFS DFS

Data Structure Queue Stack / Recursion

Traversal Style Level-order Depth-wise

Suitable For Shortest path in unweighted graphs Topological sort, maze solving
Feature BFS DFS

Time Complexity O(V + E) O(V + E)

Space Complexity O(V) O(V)

Conclusion:
 BFS is ideal for finding the shortest path in unweighted graphs.
 DFS is suitable for exploring components, cycle detection, and topological sorting.
Both methods are fundamental for solving a wide range of problems in computer science and real-world
applications.

Graph Diagram for Reference:


A
/\
B C
/ \
D E
BFS: A → B → C → D → E
DFS: A → B → D → C → E
Q9. Write short notes on following:
i) Graph iterators
ii) Skip list and hashing

Ans. i) Graph Iterators


Graph Iterators are special tools or objects used to systematically traverse elements (nodes or edges) of a
graph data structure, similar to how array or list iterators work in linear data structures.
Types of Graph Iterators:
1. Vertex Iterator: Iterates over all vertices in the graph.
2. Edge Iterator: Iterates over all edges in the graph.
3. Adjacency Iterator: Iterates over all adjacent vertices (neighbors) of a given vertex.
Purpose:
 Allow traversal without exposing internal representation.
 Improve readability and modularity in graph algorithms.
 Used in programming libraries like STL (C++), Java Collections, and Python's networkx.
Example (Python-like):
for vertex in G.nodes():
print(vertex)
for edge in G.edges():
print(edge)
Applications:
 Breadth-First and Depth-First traversal
 Topological sort
 Connected components detection

ii) Skip List and Hashing


A. Skip List
A Skip List is a probabilistic data structure that allows fast search, insertion, and deletion operations —
similar to balanced trees but simpler to implement.
Structure:
 Consists of multiple levels of linked lists.
 Higher levels allow "skipping" over many elements.
 Each element may appear in multiple levels depending on random coin flips.
Operations Time Complexity:
 Search, Insert, Delete: O(log n) average time.
Diagram:
Level 3: ----> 50 ----> 90
Level 2: ----> 30 ----> 50 ----> 90
Level 1: ----> 10 ----> 30 ----> 50 ----> 70 ----> 90
Advantages:
 Easier to implement than AVL/Red-Black trees.
 Good average-case performance.

B. Hashing
Hashing is a technique to map data (keys) to a fixed-size table (called a hash table) using a hash function.
Hash Function:
A function that converts a key into an index in the hash table.
Example: index = hash(key) % table_size
Collision Resolution Techniques:
1. Chaining: Store multiple elements at the same index using linked lists.
2. Open Addressing: Find another empty slot using methods like:
o Linear probing

o Quadratic probing

o Double hashing

Operations Time Complexity:


 Search, Insert, Delete: O(1) average time
Diagram (Chaining):
Index 0: → 20 → 30
Index 1: → 21
Index 2: → 42 → 72
Applications:
 Symbol tables in compilers
 Caches
 Databases (indexing)
 Password verification systems

Together, skip lists and hashing provide efficient methods for managing and accessing data in dynamic
applications.

Q10. Define a graph. What are important applications of Graph? Explain different representation of
Graph in memory using suitable examples.

Definition of Graph:
A graph is a non-linear data structure consisting of a set of vertices (nodes) and a set of edges that connect
pairs of vertices.
Mathematically, a graph is represented as:
G=(V,E)G = (V, E)
Where:
 VV = Set of vertices
 EE = Set of edges connecting the vertices
Applications of Graphs:
1. Social Networks – Users as nodes, relationships as edges.
2. Google Maps / GPS – Locations as vertices, roads as edges.
3. Computer Networks – Routers and computers as nodes, connections as edges.
4. Web Page Linking – Web pages as nodes, hyperlinks as edges.
5. Project Scheduling – Tasks and dependencies modeled using graphs.
6. Recommendation Systems – Users and products as graph elements.
7. Electric Circuits – Components and wires modeled as graphs.

Graph Representations in Memory:


There are mainly two standard methods to represent a graph in memory:

1. Adjacency Matrix:
 A 2D array of size V×VV \times V
 Each cell matrix[i][j] = 1 if there is an edge from vertex i to j, else 0
Example:
Graph:
A
/\
B C
Vertices: A=0, B=1, C=2

ABC

A0 1 1

B1 0 0

C1 0 0

Advantages:
 Easy to implement
 Good for dense graphs
Disadvantages:
 Takes O(V²) space even for sparse graphs

2. Adjacency List:
 Uses an array of lists
 Each vertex stores a list of its adjacent vertices
Example:
Graph:
A→B
A→C
B→D
Adjacency List:
A→B→C
B→D
C→
D→
Advantages:
 Saves space for sparse graphs
 Efficient neighbor traversal
Disadvantages:
 Slower for checking direct edge existence between nodes

Diagram Comparison:
Graph: Adjacency Matrix: Adjacency List:
A ABCD A→B→C
/\ ------- B→D
B C A|0 1 1 0 C→
| B|1 0 0 1 D→
D C|1 0 0 0
D|0 1 0 0

Conclusion:
Graph representation depends on the type of graph (sparse/dense) and the operations required.
 Use adjacency matrix for quick edge lookup
 Use adjacency list for efficient memory usage in sparse graphs
Define following terms with illustration:
i) Digraph
ii) Complete graph
iii) Acyclic graph
iv) Weighted graph
v) Degree of vertex
vi) Indegree
vii) Outdegree
viii) Simple path
Ans.
i) Digraph (Directed Graph):
A digraph is a graph in which each edge has a direction, i.e., it goes from one vertex to another.
Example:
A→B→C

ii) Complete Graph:


A complete graph is a graph in which every pair of distinct vertices is connected by a unique edge.
For n vertices, the total number of edges = n(n−1)2\frac{n(n-1)}{2}
Example (K4):
A —— B
|\ /|
|\/|
D —— C

iii) Acyclic Graph:


A graph with no cycles is called an acyclic graph.
In a Directed Acyclic Graph (DAG), no vertex is revisited.
Example:
A→B→C

iv) Weighted Graph:


A graph in which each edge carries a weight or cost (e.g., distance, time, etc.)
Example:
A --5--> B --2--> C
v) Degree of Vertex:
In an undirected graph, the degree of a vertex is the number of edges incident to it.
Example:
In
A—B—C
 deg(B) = 2

vi) Indegree:
In a directed graph, indegree of a vertex is the number of edges coming into it.
Example:
In
A→B←C
 indegree(B) = 2

vii) Outdegree:
In a directed graph, outdegree of a vertex is the number of edges going out from it.
Example:
In
A→B←C
 outdegree(A) = 1

viii) Simple Path:


A simple path is a path in which no vertex is repeated.
Example:
In
A→B→C→D
 A-B-C-D is a simple path

Illustration Summary Diagram:


Digraph: A→B
Complete: A—B—C—D (all connected)

Acyclic: A → B → C (no loop)

Weighted: A --3--> B

Degree: A—B—C, deg(B)=2

Indegree: A → B ← C (indeg(B)=2)

Outdegree: A → B ← C (outdeg(A)=1)

Simple Path: A → B → C → D (no repeats)

You might also like