You are on page 1of 1

Linked Lists

Definition: A linked list is a linear data structure where elements are stored in nodes, and each node points to the next node in the
sequence.
Types of Linked Lists:
1. Singly Linked List: Each node points to the next node in the sequence. The last node points to null.
2. Doubly Linked List: Each node has pointers to both the next and the previous nodes. Allows for traversal in both directions.
3. Circular Linked List: Last node of the list points back to the first node. Useful for applications where the list needs to be traversed
cyclically. Basic Structure of a Node: python Copy code class Node: def init(self, data): self.data = data self.next = None #
Reference to the next node in the list Basic Operations:
4. Insertion: Insert at the beginning: python Copy code def insert_at_beginning(self, data): new_node = Node(data) new_node.next =
self.head self.head = new_node Insert at the end: python Copy code def insert_at_end(self, data): new_node = Node(data) if not
self.head: self.head = new_node return current = self.head while current.next: current = current.next current.next = new_node
5. Deletion: Delete by value: python Copy code def delete_by_value(self, value): current = self.head if current and current.data ==
value: self.head = current.next current = None return prev = None while current and current.data != value: prev = current current =
current.next if current is None: return prev.next = current.next current = None
6. Traversal: python Copy code def traverse(self): current = self.head while current: print(current.data, end=' ') current = current.next
Time Complexity: Insertion/Deletion at the beginning: O(1) Insertion/Deletion at the end: O(n) Traversal: O(n) Linked lists are
dynamic data structures that can be easily modified and do not have a fixed size, making them suitable for certain applications
where the size of the data is unknown or may change. However, random access is not as efficient as in arrays. Choose the type of
linked list based on the requirements of your application.

You might also like