Mid Turm Exam DSA
Mid Turm Exam DSA
Mid Turm Exam DSA
Key Differences
class Node:
def __init__(self, data):
self.data = data # Assign data to the node
self.next = None # Initialize next as None
class SinglyLinkedList:
def __init__(self):
self.head = None # Initialize head to None
def print_list(self):
current = self.head # Start from the head
while current: # Traverse the list
print(current.data, end=" -> ")
current = current.next
print("None") # Indicate the end of the list
class Node:
def __init__(self, data):
self.data = data
self.next = None
Imagine you're creating a music player that allows users to navigate through a
playlist of songs. Users want the ability to:
In this case, a doubly linked list would be ideal because each node contains
references (pointers) to both the next and the previous nodes. This allows:
- Efficient navigation to the next song with a simple pointer to the next node.
- Easy backward traversal to the previous song without needing to traverse the
entire list from the start.
Thus, for applications requiring frequent bidirectional access, a doubly linked list
provides a clear advantage.
return previous
# Example usage
if __name__ == "__main__":
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
current = head
while current:
current = current.next
print("None")
head = reverse_linked_list(head)
current = head
while current:
current = current.next
print("None")