Which of the following is the main advantage of using a doubly linked list instead of a singly linked list?
Think about how you can move through the list in both directions.
Doubly linked lists have two pointers per node, allowing easy movement forward and backward. Singly linked lists only allow forward traversal.
What will be the printed output of the following Go code that traverses a doubly linked list backward?
package main import "fmt" type Node struct { data int prev *Node next *Node } func main() { n1 := &Node{data: 1} n2 := &Node{data: 2} n3 := &Node{data: 3} n1.next = n2 n2.prev = n1 n2.next = n3 n3.prev = n2 current := n3 for current != nil { fmt.Print(current.data) if current.prev != nil { fmt.Print(" <-> ") } current = current.prev } }
The code starts from the last node and moves backward using the prev pointer.
The traversal starts at node with data 3 and moves backward through prev pointers, printing 3, 2, then 1 with arrows between.
What error will the following Go code produce when inserting a new node after the head in a doubly linked list?
package main import "fmt" type Node struct { data int prev *Node next *Node } func main() { head := &Node{data: 1} second := &Node{data: 2} head.next = second second.prev = head newNode := &Node{data: 3} newNode.next = head.next head.next = newNode newNode.prev = head fmt.Println(head.next.next.data) }
Check if all pointers are updated correctly after insertion.
The code forgets to update the prev pointer of the original second node to point to the new node, causing a broken link and runtime error when accessing head.next.next.data.
What will be the printed output after removing the middle node from this doubly linked list?
package main import "fmt" type Node struct { data int prev *Node next *Node } func main() { n1 := &Node{data: 1} n2 := &Node{data: 2} n3 := &Node{data: 3} n1.next = n2 n2.prev = n1 n2.next = n3 n3.prev = n2 // Remove n2 n1.next = n3 n3.prev = n1 current := n1 for current != nil { fmt.Print(current.data) if current.next != nil { fmt.Print(" -> ") } current = current.next } }
After removal, the list should skip the removed node.
The middle node with data 2 is removed by linking node 1 directly to node 3, so the output prints 1 -> 3.
Which statement best describes the memory trade-off when using a doubly linked list compared to a singly linked list?
Consider the number of pointers stored in each node and the operations enabled.
Doubly linked lists store two pointers per node, increasing memory use, but this enables efficient backward traversal and easier node deletion compared to singly linked lists.
