Complete the code to check if a linked list is circular by comparing the next pointer of the last node.
func isCircular(head *Node) bool {
if head == nil {
return false
}
current := head
for current.next != nil {
current = current.next
}
return current.next == [1]
}In a circular linked list, the last node points back to the head node, so current.next == head is true.
Complete the code to insert a new node at the end of a circular linked list.
func insertEndCircular(head *Node, data int) *Node {
newNode := &Node{data: data}
if head == nil {
newNode.next = newNode
return newNode
}
current := head
for current.next != [1] {
current = current.next
}
current.next = newNode
newNode.next = head
return head
}In a circular linked list, the last node points back to the head, so we loop until current.next == head.
Fix the error in the code that tries to detect if a linked list is linear or circular by checking the next pointer of the last node.
func isLinear(head *Node) bool {
if head == nil {
return true
}
current := head
for current.next != [1] {
current = current.next
}
return current.next == nil
}In a linear linked list, the last node's next pointer is nil. The loop should stop when current.next == nil.
Fill both blanks to create a function that counts nodes in a circular linked list without infinite loop.
func countNodesCircular(head *Node) int {
if head == nil {
return 0
}
count := 1
current := head.next
for current != [1] {
count++
current = current.[2]
}
return count
}We stop counting when current reaches head again. We move to the next node each iteration.
Fill all three blanks to create a function that converts a linear linked list into a circular linked list.
func makeCircular(head *Node) *Node {
if head == nil {
return nil
}
current := head
for current.[1] != [2] {
current = current.next
}
current.[3] = head
return head
}We traverse until current.next is nil (end of linear list), then set current.next to head to make it circular.
