Complete the code to delete the head node of a singly linked list.
func deleteHead(head *Node) *Node {
if head == nil {
return nil
}
return [1]
}To delete the head node, we return the next node as the new head.
Complete the code to traverse the list to the node before the one to delete at position pos.
func deleteAtPosition(head *Node, pos int) *Node {
if pos == 0 {
return head.next
}
current := head
for i := 0; i < [1]; i++ {
current = current.next
}
// deletion logic follows
return head
}We stop at the node before the one to delete, so we loop pos - 1 times.
Fix the error in the deletion step to correctly remove the node at position pos.
func deleteAtPosition(head *Node, pos int) *Node {
if pos == 0 {
return head.next
}
current := head
for i := 0; i < pos-1; i++ {
current = current.next
}
current.next = [1]
return head
}To delete the node at pos, link current.next to the node after the one being deleted.
Fill both blanks to safely delete a node at position pos, checking for nil pointers.
func deleteAtPosition(head *Node, pos int) *Node {
if pos == 0 {
return head.next
}
current := head
for i := 0; i < [1]; i++ {
if current == nil {
return head
}
current = current.next
}
if current == nil || current.next == nil {
return head
}
current.next = [2]
return head
}Loop pos - 1 times to reach the node before deletion. Then link current.next to current.next.next to delete.
Fill all three blanks to implement a complete delete function that handles edge cases.
func deleteAtPosition(head *Node, pos int) *Node {
if head == nil {
return nil
}
if pos == 0 {
return [1]
}
current := head
for i := 0; i < [2]; i++ {
if current == nil {
return head
}
current = current.next
}
if current == nil || current.next == nil {
return head
}
current.next = [3]
return head
}Return head.next if deleting first node. Loop pos - 1 times to reach previous node. Link current.next to current.next.next to delete.
