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

Python Exp6

The document outlines an experiment for the academic year 2024-2025 in the Department of Computer Engineering, focusing on data structures in Python, specifically linked lists, stacks, and queues. It provides theoretical explanations, types, operations, and syntax for each data structure, along with a menu-driven program to implement these structures using built-in functions. The program allows users to perform various operations on linked lists, stacks, and queues interactively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Exp6

The document outlines an experiment for the academic year 2024-2025 in the Department of Computer Engineering, focusing on data structures in Python, specifically linked lists, stacks, and queues. It provides theoretical explanations, types, operations, and syntax for each data structure, along with a menu-driven program to implement these structures using built-in functions. The program allows users to perform various operations on linked lists, stacks, and queues interactively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Department of Computer Engineering

Academic Year – 2024-2025

Experiment No- 6

Aim: To Study and implement Data Structure using built in function for Linked list,
Stack and Queue.

Theory:

What is data structure in python?

Data structures are ways of organizing and storing data efficiently. Python provides built-in data
structures that help in managing and manipulating data effectively.

1) Linked list: A linked list is a linear data structure where elements (nodes) are connected using
pointers. Unlike arrays, linked lists do not have a fixed size and can dynamically grow or shrink.

Types of Linked List:


i) Singly Linked List - Each node points to the next node.
Each node contains:
• Data (value)
• Pointer (reference to the next node)
Syntax- class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
# Add node at the end
pass
def display(self):
# Traverse and print the list
pass
def delete(self, key):
# Delete a node by value
Pass

ii) Doubly Linked List - Each node points to both the previous and next nodes.
Each node contains:
• Data
• Pointer to the next node
• Pointer to the previous node
Syntax- class DNode:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
# Add node at the end
pass
def display(self):
# Traverse and print the list
pass
def delete(self, key):
# Delete a node by value
Pass

iii) Circular Linked List - The last node connects back to the first node.
Structure:
• The last node points to the first node, forming a circle.
• Can be singly or doubly linked.
Syntax- class CNode:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
# Add node at the end
Pass
def display(self):
# Traverse and print the circular list
pass

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

Operations in a Stack-
a. Push – Add an element to the top.
b. Pop – Remove the top element.
c. Peek (Top) – Get the top element without removing it.
d. isEmpty – Check if the stack is empty.
Syntax:
# 1. Using List
stack = []
stack.append(data) # Push
stack.pop() # Pop
top = stack[-1] # Peek
is_empty = len(stack) == 0 # Check if empty

# 2. Using collections.deque
from collections import deque
stack = deque()
stack.append(data) # Push
stack.pop() # Pop
top = stack[-1] # Peek
is_empty = len(stack) == 0 # Check if empty

# 3. Using queue.LifoQueue (Thread-Safe)


from queue import LifoQueue
stack = LifoQueue()
stack.put(data) # Push
stack.get() # Pop
is_empty = stack.empty() # Check if empty
# 4. Using Custom Stack Class
class Stack:
def __init__(self):
self.stack = []
def push(self, data):
self.stack.append(data)
def pop(self):
if not self.is_empty():
return self.stack.pop()
def peek(self):
if not self.is_empty():
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0

# Usage of Custom Stack


s = Stack()
s.push(data) # Push
s.pop() # Pop
top = s.peek() # Peek
is_empty = s.is_empty() # Check if empty

3) Queue: A queue is a linear data structure that follows the First In, First Out (FIFO) principle.
This means that the first element added is the first one to be removed.

Types of Queues:

a) Simple Queue (FIFO) – Elements are added at the rear and removed from the front.

b) Circular Queue – The rear connects back to the front for efficient memory usage.

c) Deque (Double-Ended Queue) – Insertions and deletions can happen at both ends.

d) Priority Queue – Elements are dequeued based on priority, not order.


Operations in a Queue

a) Enqueue – Add an element to the rear.

b) Dequeue – Remove an element from the front.

c) Front (Peek) – Get the front element without removing it.

d) isEmpty – Check if the queue is empty.

Syntax-

# 1. Using List (Not Recommended for Large Queues)

queue = []

queue.append(data) # Enqueue

queue.pop(0) # Dequeue

front = queue[0] # Peek

is_empty = len(queue) == 0 # Check if empty

# 2. Using collections.deque (Recommended)

from collections import deque

queue = deque()

queue.append(data) # Enqueue
queue.popleft() # Dequeue

front = queue[0] # Peek

is_empty = len(queue) == 0 # Check if empty

# 3. Using queue.Queue (Thread-Safe)

from queue import Queue

q = Queue()

q.put(data) # Enqueue

q.get() # Dequeue

is_empty = q.empty() # Check if empty

# 4. Using queue.PriorityQueue (Priority Queue)

from queue import PriorityQueue

pq = PriorityQueue()

pq.put((priority, data)) # Enqueue with priority

pq.get() # Dequeue based on priority

Ways to Implement a Queue in Python-

a. Using List (Not Recommended for Large Queues)

b. Using collections.deque (Recommended)

c. Using queue.Queue (Thread-Safe)

d. Using queue.PriorityQueue (Priority Queue)


Program: Write a Menu Driven program for data structure using built in function for linked list, Stack
and Queue.

from collections import deque


from queue import Queue
# Initialize Data Structures
linked_list = [] # Using list for Linked List
stack = deque() # Using deque for Stack
queue = deque() # Using deque for Queue

# Menu Function
def menu():
while True:
print("\nData Structure Operations:")
print("1. Linked List")
print("2. Stack")
print("3. Queue")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
linked_list_operations()
elif choice == '2':
stack_operations()
elif choice == '3':
queue_operations()
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice! Try again.")

# Linked List Operations


def linked_list_operations():
while True:
print("\nLinked List Operations:")
print("1. Append")
print("2. Insert at Position")
print("3. Delete Element")
print("4. Display")
print("5. Back to Main Menu")
choice = input("Enter your choice: ")
if choice == '1':
data = input("Enter element: ")
linked_list.append(data)
elif choice == '2':
data = input("Enter element: ")
pos = int(input("Enter position: "))
linked_list.insert(pos, data)
elif choice == '3':
data = input("Enter element to delete: ")
if data in linked_list:
linked_list.remove(data)
else:
print("Element not found!")
elif choice == '4':
print("Linked List:", linked_list)
elif choice == '5':
break
else:
print("Invalid choice! Try again.")

# Stack Operations
def stack_operations():
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Back to Main Menu")
choice = input("Enter your choice: ")
if choice == '1':
data = input("Enter element: ")
stack.append(data)
elif choice == '2':
if stack:
print("Popped element:", stack.pop())
else:
print("Stack is empty!")
elif choice == '3':
if stack:
print("Top element:", stack[-1])
else:
print("Stack is empty!")
elif choice == '4':
print("Stack:", list(stack))
elif choice == '5':
break
else:
print("Invalid choice! Try again.")

# Queue Operations
def queue_operations():
while True:
print("\nQueue Operations:")
print("1. Enqueue")
print("2. Dequeue")
print("3. Peek")
print("4. Display")
print("5. Back to Main Menu")
choice = input("Enter your choice: ")
if choice == '1':
data = input("Enter element: ")
queue.append(data)
elif choice == '2':
if queue:
print("Dequeued element:", queue.popleft())
else:
print("Queue is empty!")
elif choice == '3':
if queue:
print("Front element:", queue[0])
else:
print("Queue is empty!")
elif choice == '4':
print("Queue:", list(queue))
elif choice == '5':
break
else:
print("Invalid choice! Try again.")

# Run the Menu


menu()

Output:
PS C:\C Programming> & C:/Users/asha/anaconda3/python.exe "c:/C
Programming/.vscode/Python/ds.py"

Data Structure Operations:


1. Linked List
2. Stack
3. Queue
4. Exit
Enter your choice: 1

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 21

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 43

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 52

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 2
Enter element: 58
Enter position: 2

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 4
Linked List: ['21', '43', '58', '52']

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 3
Enter element to delete: 43

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 4
Linked List: ['21', '58', '52']

Linked List Operations:


1. Append
2. Insert at Position
3. Delete Element
4. Display
5. Back to Main Menu
Enter your choice: 5

Data Structure Operations:


1. Linked List
2. Stack
3. Queue
4. Exit
Enter your choice: 2
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 50

Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 67

Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 83

Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 2
Popped element: 83
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 3
Top element: 67

Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 4
Stack: ['50', '67']

Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 5

Data Structure Operations:


1. Linked List
2. Stack
3. Queue
4. Exit
Enter your choice: 3

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 66

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 83

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 1
Enter element: 72

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 2
Dequeued element: 66

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 3
Front element: 83

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice: 4
Queue: ['83', '72']

Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Back to Main Menu
Enter your choice:5

Data Structure Operations:


1. Linked List
2. Stack
3. Queue
4. Exit
Enter your choice: 4
Exiting...

You might also like