.
Define linear data structure and explain difference between queue and stack
with example.
Linear Data Structures are a type of data structure in computer science where data
elements are arranged sequentially or linearly. Each element has a previous and
next adjacent, except for the first and last elements.
haracteristics of Linear Data Structure:
C
Sequential Organization: In linear data structures, data elements are arranged
sequentially, one after the other. Each element has a unique predecessor (except for
the first element) and a unique successor (except for the last element)
Order Preservation: The order in which elements are added to the data structure is
preserved. This means that the first element added will be the first one to be
accessed or removed, and the last element added will be the last one to be
accessed or removed.
Fixed or Dynamic Size: Linear data structures can have either fixed or dynamic
sizes. Arrays typically have a fixed size when they are created, while other structures
like linked lists, stacks, and queues can dynamically grow or shrink as elements are
added or removed.
Efficient Access: Accessing elements within a linear data structure is typically
efficient. For example, arrays offer constant-time access to elements using their
index.
Linear data structures are commonly used for organising and manipulating
data in a sequential fashion. Some of the most common linear data
structures include:
Arrays: A collection of elements stored in contiguous memory locations.
● Linked Lists: A collection of nodes, each containing an element
and a reference to the next node.
Stacks: A collection of elements with Last-In-First-Out (LIFO) order.
Queues: A collection of elements with First-In-First-Out (FIFO) order.
Key Differences Between Stack and Queue
Here is a table that highlights the key differences between stack and
queue data structures:
Feature Stack Queue
A linear data
structure that
A linear data structure that follows the
Definition follows the Last In
F irst In First Out (FIFO) principle.
F irst Out (LIFO)
principle.
Push (add an item),
Enqueue (add an item), Dequeue (remove
Primary Pop (remove an
an item), Front (view the first item), Rear
Operations item), Peek (view the
(view the last item)
top item)
Elements are added
Insertion/Re and removed from Elements are added at the rear and
moval the same end (the removed from the front.
top).
Function call
Scheduling processes in operating
management (call
Use Cases systems, managing requests in a printer
stack), expression
queue, breadth-first search in graphs.
evaluation and
syntax parsing, undo
mechanisms in text
editors.
Browser history
Customer service lines, CPU task
Examples (back button),
scheduling.
reversing a word.
A stack of plates:
Real-World A queue at a ticket counter: the first
you add and remove
Analogy person in line is the first to be served.
plates from the top.
Complexity Push: O(1), Pop: Enqueue: O(1), Dequeue: O(1), Front:
(Amortized) O(1), Peek: O(1) O(1), Rear: O(1)
Typically uses a
Memory contiguous block of Typically uses a circular buffer or linked
Structure memory or linked list.
list.
Can be implemented
Implementat Can be implemented using arrays, linked
using arrays or
ion lists, or circular buffers.
linked lists.
2.explain operation on non-linear data structure with example
Sure! Here's theclean text-onlyversion of the explanationfor:
2. Explain operations on non-linear data structure with example
non-linear data structure is a structure where data elements are not placed
A
sequentially. Instead, elements are connected in a hierarchical or networked manner,
where a single element can be connected to multiple elements.
efinition: A data structure where traversal is not done sequentially but hierarchically
D
or through links/branches is called a non-linear data structure.
Common non-linear data structures include:
1. Trees (e.g., Binary Tree, Binary Search Tree)
2. Graphs (e.g., Directed, Undirected, Weighted)
3. Heaps
4. Tries
Operations on Tree Data Structures
tree is a hierarchical structure where each node has a parent (except the root) and
A
can have zero or more children.
Common Tree Operations:
● Insertion: Add a new node to the tree
● Deletion: Remove a node from the tree
● Traversal: Visit all nodes (Preorder, Inorder, Postorder, Level Order)
● Search: Find a node with a specific value
Example: Binary Search Tree (BST)
Insert 50, 30, 70, 20, 40, 60, 80 results in the following structure:
50
/ \
30 70
/ \ / \
20 40 60 80
Inorder Traversal (Left → Root → Right): 20, 30, 40, 50, 60, 70, 80
Inorder Traversal Algorithm:
def inorder(node):
if node is not None:
inorder(node.left)
print(node.data)
inorder(node.right)
Operations on Graph Data Structures
graph is a collection of nodes (vertices) connected by edges. It can be directed or
A
undirected, and weighted or unweighted.
Common Graph Operations:
● Add Vertex: Add a new node
● Add Edge: Connect two vertices
● Delete Vertex: Remove a node
● Delete Edge: Remove a connection
● Traversal: Visit all nodes (BFS, DFS)
● Search Path: Find a path between nodes
Example Graph:
A -- B
| |
C -- D
Breadth-First Search (BFS) Output: A, B, C, D
Depth-First Search (DFS) Output: A, B, D, C
BFS Algorithm:
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
print(node)
visited.add(node)
queue.extend(graph[node] - visited)
Why Use Non-Linear Data Structures?
● Efficient data representation
● Hierarchical relationship modeling
● Complex relationship mapping
● Faster search and insert operations
● Path finding and connectivity
Real-Life Applications
Tree: Used in file systems, decision trees, XML parsing
Graph: Used in social networks, GPS, network routing
Heap: Used in priority queues, scheduling tasks
Trie: Used in auto-complete, spell checkers
Conclusion
on-linear data structures allow us to model complex relationships. Trees are used
N
in hierarchical data representation like folder systems or expression trees. Graphs
are used in modeling networks and paths like road maps or web links. Key
operations include insertion, deletion, traversal, and searching. They are powerful
tools for solving real-world computational problems.
3. What is Stack Data Structure? Write Algorithm for Push Operation
Definition of Stack Data Structure
stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In
A
a stack, the element that is inserted last is the one that is removed first.
In simpler terms:
● The last item pushed into the stack is the first one to be popped out.
Real-Life Example
A stack of plates:
● Add (push) plates on the top.
● Remove (pop) plates from the top.
You can only access the top plate, not the ones below it.
Basic Stack Operations
1. Push – Adds an element to the top of the stack
2. Pop – Removes the top element from the stack
3. Peek/Top – Returns the top element without removing it
4. isEmpty – Checks if the stack is empty
5. isFull – Checks if the stack is full (in fixed-size implementation)
Implementation of Stack
Stacks can be implemented in two ways:
● Using an array (fixed size)
● Using a linked list (dynamic size)
Push Operation
Purpose: Insert a new element at the top of the stack.
Steps (Array Implementation):
1. Check if the stack is full (overflow condition).
topindex.
2. If not full, increment the
top
3. Assign the new element to the position pointed by .
Algorithm for Push Operation (Using Array)
Let:
●
MAXbe the maximum size of the stack.
●
stack[]be the array representing the stack.
●
topbe the index of the top element (initialized to -1).
Algorithm PUSH(stack, top, MAX, ITEM)
Step 1: IF top == MAX - 1 THEN
PRINT "Stack Overflow"
RETURN
END IF
Step 2: top ← top + 1
Step 3: stack[top] ← ITEM
Step 4: PRINT "ITEM pushed successfully"
Step 5: RETURN
Explanation of Algorithm
● Step 1 checks whether the stack is full. If it is, insertion cannot be done.
toppointer to the next available position.
● Step 2 increases the
ITEMat the new top position.
● Step 3 inserts the
● Step 4 confirms the operation was successful.
Push Operation Using Linked List
In a linked list-based stack:
dataand a
● Each element is a node with nextpointer.
top
● The new node becomes the new .
Algorithm PUSH_LL(top, ITEM)
tep 1: Create a new node NEW
S
Step 2: NEW.data ← ITEM
Step 3: NEW.next ← top
Step 4: top ← NEW
Step 5: PRINT "ITEM pushed successfully"
Step 6: RETURN
Time Complexity of Push Operation:
● O(1) for both array and linked list implementations
Applications of Stack
● Expression evaluation (postfix, prefix)
● Undo/redo features in editors
● Function call stack in programming languages
● Balanced parentheses checking
● Backtracking problems (mazes, puzzles)
Conclusion
stack is a fundamental data structure with LIFO behavior. The push operation adds
A
an element to the top. It is simple but powerful, forming the basis for many
system-level and application-level functionalities.
4. What is a Linked List? Give Memory Representation of Linked List
What is a Linked List?
linked listis a linear data structure in which elements, callednodes, are stored in
A
a sequence, where each node contains:
● Data: The actual value or information.
● Next: A reference (or pointer) to the next node in the sequence.
nlike arrays, linked lists do not store elements in contiguous memory locations.
U
Instead, each element points to the next, allowing dynamic memory allocation. This
allows linked lists to efficiently grow or shrink in size.
Types of Linked Lists
1. S
ingly Linked List: Each node has a reference to the next node, and the last
node’s reference isNULL
, indicating the end of thelist.
2. D
oubly Linked List: Each node has references to both the next and the
previous node.
3. C
ircular Linked List: The last node points back tothe first node, creating a
circular reference.
Structure of a Linked List Node
Each node in a singly linked list consists of:
● Data: The value stored in the node.
● Next: A pointer/reference to the next node in thelist.
he linked list typically has ahead pointer, which points to the first node in the list. If
T
NULL
the list is empty, the head pointer is .
Memory Representation of Linked List
In asingly linked list, the memory representation consists of individual nodes. Each
node is created dynamically (via pointers or references in high-level languages), and
the nodes are connected by the nextpointer.
Example of a singly linked list with three nodes:
Data = 10
1. Node 1: Next = address of Node 2
,
Data = 20
2. Node 2: Next = address of Node 3
,
Data = 30
3. Node 3: Next = NULL
,
In memory:
Node Dat Next
# a
ode
N 10 ddress of Node
A
1 2
ode
N 20 ddress of Node
A
2 3
ode
N 30 NULL
3
he head of the list points to the first node (Node 1). If the list is empty, the head
T
NULL
pointer is .
Linked List Memory Representation Diagram
Consider the following memory representation of a linked list with three nodes:
head -> [10 | *] -> [20 | *] -> [30 | NULL]
Where:
●
headpoints to the first node.
● Each box represents a node with:
○ Data: The value stored in that node (e.g., 10, 20, 30).
NULLif it isthe last node.
○ Next: A pointer to the next node, or
Linked List Operations
1. Insertion: Add a node to the list (at the beginning, end, or middle).
2. Deletion: Remove a node from the list.
nextpointers).
3. Traversal: Visit each node in the list (usually by following the
4. Search: Find a node with a specific value.
Advantages of Linked Lists
● D
ynamic Size: The size of the linked list can growor shrink dynamically,
making it more flexible than arrays.
● E
fficient Insertions/Deletions: Insertion and deletionoperations can be
performed efficiently, especially at the beginning or middle of the list.
Disadvantages of Linked Lists
● M
emory Overhead: Each node requires extra memory for the
pointer/reference to the next node.
● A
ccess Time: Accessing an element in a linked list requires traversal from
the head to the desired node (O(n) time complexity).
Conclusion
linked list is a flexible, dynamic data structure that consists of nodes, where each
A
node stores data and a reference to the next node. The memory representation of a
linked list is non-contiguous, with each node dynamically allocated and linked
through pointers. Linked lists are widely used in situations where the size of the data
structure is not known in advance or when frequent insertions and deletions are
required.