Day 75: Linked Lists
Brief:
Day 75 marks our exploration into linked lists, a fundamental data structure widely used in computer science. Linked lists offer dynamic memory allocation and efficient insertion and deletion operations, making them invaluable in various applications. We'll delve into their types, implementation, operations, and solve problems to solidify our understanding.
Topics Covered:
- Types of Linked Lists:
- Singly Linked Lists: Each element points to the next element in the sequence.
- Doubly Linked Lists: Each element has pointers to both the next and previous elements.
- Circular Linked Lists: The last element points back to the first element, forming a loop.
- Implementation of Linked Lists:
- Node Structure: Each node contains data and a pointer to the next (and optionally, previous) node.
- Insertion: Adding elements at the beginning, end, or middle of the list.
- Deletion: Removing elements from the list while maintaining connectivity.
- Traversal: Iterating through the list to access or manipulate elements.
- Operations and Problems:
- Finding the Middle Element: Traverse the list with two pointers, one moving twice as fast as the other.
- Detecting Cycles: Use Floyd's cycle-finding algorithm to detect cycles in the list.
- Reversing the List: Reverse the links between nodes to change the direction of traversal.
In-Depth Examples:
- Singly Linked List Implementation:
class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedList { constructor() { this.head = null; } append(data) { const newNode = new Node(data); if (!this.head) { this.head = newNode; return; } let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } } // Create a singly linked list: 1 -> 2 -> 3 -> null const linkedList = new LinkedList(); linkedList.append(1); linkedList.append(2); linkedList.append(3);
- Finding the Middle Element:
function findMiddle(head) { let slow = head; let fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } return slow.data; } // Find the middle element of the linked list const middle = findMiddle(linkedList.head); console.log("Middle element:", middle);
- Reversing the List:
function reverseList(head) { let prev = null; let current = head; while (current) { const nextNode = current.next; current.next = prev; prev = current; current = nextNode; } return prev; } // Reverse the linked list linkedList.head = reverseList(linkedList.head);
Comments
Post a Comment