Computer Science - Data Structures
Computer Science - Data Structures
1. Definition: A linked list is a linear data structure where elements are stored in nodes.
Each node contains a data part and a reference (or link) to the next node in the
sequence.
2. Types of Linked Lists:
○ Singly Linked List: Each node points to the next node.
○ Doubly Linked List: Each node points to both the next and the previous nodes.
○ Circular Linked List: The last node points back to the first node, forming a
circle.
1. Insertion:
○ At the beginning: Update the new node's link to the current head and then
change the head to the new node.
○ At the end: Traverse to the last node and update its link to the new node.
○ In the middle: Update the preceding node's link to the new node and the new
node's link to the next node.
2. Deletion:
○ From the beginning: Update the head to the next node.
○ From the end: Traverse to the second-last node and update its link to null.
○ From the middle: Update the preceding node's link to skip the node to be deleted
and point to the next node.
3. Traversal:
○ Start from the head and follow each node's link until the end (null link) is reached.
○ Useful for searching and accessing elements.
1. Advantages:
○ Dynamic size: Can grow or shrink as needed.
○ Efficient insertions and deletions: Especially at the beginning or end.
2. Disadvantages:
○ No random access: Must traverse from the head to access elements.
○ Extra memory usage: Requires storage for links.
Examples:
python
Copy code
class Node:
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def print_list(self):
current = self.head
while current:
current = current.next
print("None")
Discussion Points: