Linked list
A linked list is a linear data structure where each element (node) contains a value and a reference (link) to the next node in the sequence. Linked lists are dynamic and can grow or shrink in size by allocating or deallocating memory as needed.
Key Properties of Linked Lists
Node Structure: Each node contains a value and a reference to the next node.
Head: The first node in the linked list.
Tail: The last node in the linked list, which points to
null(orNonein Python).Dynamic Size: The size of the linked list can change dynamically.
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 node.
Circular Linked List: The last node points back to the first node, forming a circle.
Operations
Insertion
To insert a value into a singly linked list:
Create a new node with the given value.
If inserting at the head, set the new node's next reference to the current head and update the head to the new node.
If inserting at the tail, traverse the list to find the last node, set its next reference to the new node, and update the tail to the new node.
If inserting at a specific position, traverse the list to find the node before the desired position, set the new node's next reference to the next node, and update the previous node's next reference to the new node.
Deletion
To delete a value from a singly linked list:
If deleting the head, update the head to the next node.
If deleting the tail, traverse the list to find the second-to-last node, set its next reference to
null, and update the tail to this node.If deleting a node at a specific position, traverse the list to find the node before the desired position, update its next reference to skip the node to be deleted.
Search
To search for a value in a singly linked list:
Start at the head node.
Traverse the list, comparing each node's value with the target value.
If the value is found, return the node.
If the value is not found and the end of the list is reached, return
null.
Example
Here is an example of a singly linked list implementation in Python:
This example demonstrates the basic operations of a singly linked list, including insertion, deletion, and search.