def create_linked_list(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Usage
my_list = create_linked_list([1, 2, 3, 4, 5])
3. Traversal Pattern
python
def print_list(head):
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
def insert_at_tail(head, val):
if not head:
return ListNode(val)
current = head
while current.next:
current = current.next
current.next = ListNode(val)
return head
3. Deletion
python
def delete_node(head, val):
# If head needs to be deleted
if head and head.val == val:
return head.next
current = head
while current.next:
if current.next.val == val:
current.next = current.next.next
return head
current = current.next
return head
🚨 Common Pitfalls & Tips
Always check for None
python
# Bad
current.next.val # Might crash if current.next is None
# Good
if current and current.next:
# Safe operation
Use Dummy Nodes for Complex Manipulations
python
def some_list_operation(head):
# Dummy node helps handle edge cases
dummy = ListNode(0)
dummy.next = head
# Manipulate list using dummy
Two-Pointer Technique
python
# Find middle of linked list
def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
LeetCode-Style Problem Template
python
class Solution:
def someLinkedListProblem(self, head: ListNode) -> ListNode:
# Common pattern: create dummy node
dummy = ListNode(0)
dummy.next = head
# Your logic here
current = dummy
return dummy.next
Memory Visualization
code
Memory Address: 0x1000 0x2000 0x3000
Linked List: [1 | →] [2 | →] [3 | ∅]
↑ ↑ ↑
val val val
Each node is a separate object in memory, connected by "next" references.
Key Differences from Arrays
Dynamic size
Non-contiguous memory
Insertion/deletion is O(1) at known position
Random access is O(n)
Practice Problems to Master
Reverse a Linked List
Detect Cycle
Merge Two Sorted Lists
Remove Nth Node from End
Palindrome Linked List
Pro Tips
Draw out the list
Track current, prev, next pointers
Use dummy nodes
Be careful with None checks
Would you like me to elaborate on any of these points or show a specific linked list manipulation?