Imagine you have a list of items that changes size often. Which problem does a linked list solve better than an array?
Think about what happens when you add or remove items in the middle of an array versus a linked list.
Arrays require shifting elements when inserting or deleting in the middle, which is slow. Linked lists just change pointers, making these operations faster.
What is the printed linked list after inserting nodes with values 10, 20, 30 at the head?
package main import "fmt" type Node struct { value int next *Node } func main() { var head *Node head = &Node{value: 10, next: head} head = &Node{value: 20, next: head} head = &Node{value: 30, next: head} current := head for current != nil { fmt.Print(current.value) if current.next != nil { fmt.Print(" -> ") } current = current.next } fmt.Println(" -> null") }
Each new node is added at the head, pushing previous nodes down the list.
Inserting at head means the newest node becomes the first, so the list order is last inserted to first inserted.
What is the linked list output after deleting the node with value 20?
package main import "fmt" type Node struct { value int next *Node } func main() { head := &Node{value: 10} head.next = &Node{value: 20} head.next.next = &Node{value: 30} // Delete node with value 20 current := head for current.next != nil { if current.next.value == 20 { current.next = current.next.next break } current = current.next } // Print list current = head for current != nil { fmt.Print(current.value) if current.next != nil { fmt.Print(" -> ") } current = current.next } fmt.Println(" -> null") }
Deleting a node means skipping it by changing the previous node's next pointer.
The node with value 20 is removed by linking the node with value 10 directly to the node with value 30.
What causes the infinite loop in this linked list traversal code?
package main import "fmt" type Node struct { value int next *Node } func main() { head := &Node{value: 1} second := &Node{value: 2} third := &Node{value: 3} head.next = second second.next = third third.next = second // Bug: creates a cycle current := head for current != nil { fmt.Print(current.value, " -> ") current = current.next } fmt.Println("null") }
Check if the list has a cycle by looking at next pointers.
Setting third.next to second creates a loop between nodes 2 and 3, so traversal never ends.
Why are linked lists better than arrays when memory is fragmented and you cannot allocate a large continuous block?
Think about how memory is assigned for each element in arrays vs linked lists.
Linked lists allocate nodes individually anywhere in memory, so they can use fragmented free spaces unlike arrays which need contiguous blocks.
