Bird
Raised Fist0
DSA Goprogramming

Insert at Beginning of Circular Linked List in DSA Go

Choose your learning style10 modes available
Mental Model
A circular linked list connects the last node back to the first node, forming a circle. Inserting at the beginning means adding a new node before the current first node and updating the last node to point to this new node.
Analogy: Imagine people sitting in a circle holding hands. To add a new person at the start, you place them before the first person and make sure the last person now holds hands with the new person, keeping the circle unbroken.
head -> 1 -> 2 -> 3 ->
↑                   ↓
← ← ← ← ← ← ← ← ← ← ←
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 (circular), insert value 0 at beginning
Goal: Add a new node with value 0 at the start and keep the list circular
Step 1: Create new node with value 0
newNode(0), list: 1 -> 2 -> 3 (circular)
Why: We need a new node to insert
Step 2: Find last node (node with value 3)
1 -> 2 -> 3 [last] -> points back to 1
Why: Last node must point to new first node after insertion
Step 3: Set newNode.next to current head (1)
newNode(0) -> 1 -> 2 -> 3 (circular)
Why: New node should point to old first node
Step 4: Set last node's next to newNode
1 -> 2 -> 3 -> newNode(0) -> 1 (circular)
Why: Last node must point to new first node to keep circle
Step 5: Update head pointer to newNode
head -> newNode(0) -> 1 -> 2 -> 3 (circular)
Why: Head must point to the new first node
Result:
head -> 0 -> 1 -> 2 -> 3 ->
↑                   ↓
← ← ← ← ← ← ← ← ← ← ←
Annotated Code
DSA Go
package main

import "fmt"

type Node struct {
	val  int
	next *Node
}

// insertAtBeginning inserts a new node with value val at the start of the circular linked list
func insertAtBeginning(head *Node, val int) *Node {
	newNode := &Node{val: val}

	// If list is empty, newNode points to itself
	if head == nil {
		newNode.next = newNode
		return newNode
	}

	// Find last node which points back to head
	last := head
	for last.next != head {
		last = last.next
	}

	// Insert newNode before head
	newNode.next = head
	last.next = newNode

	// New node becomes new head
	return newNode
}

// printList prints the circular linked list starting from head
func printList(head *Node) {
	if head == nil {
		fmt.Println("List is empty")
		return
	}
	curr := head
	for {
		fmt.Printf("%d -> ", curr.val)
		curr = curr.next
		if curr == head {
			break
		}
	}
	fmt.Println("(back to head)")
}

func main() {
	// Create circular list 1 -> 2 -> 3 -> back to 1
	n1 := &Node{val: 1}
	n2 := &Node{val: 2}
	n3 := &Node{val: 3}
	n1.next = n2
	n2.next = n3
	n3.next = n1

	head := n1
	fmt.Print("Original list: ")
	printList(head)

	head = insertAtBeginning(head, 0)
	fmt.Print("After inserting 0 at beginning: ")
	printList(head)
}
if head == nil { newNode.next = newNode return newNode }
handle empty list by pointing new node to itself
last := head for last.next != head { last = last.next }
find last node which points back to head
newNode.next = head
new node points to current head
last.next = newNode
last node points to new node to keep circle
return newNode
new node becomes new head
OutputSuccess
Original list: 1 -> 2 -> 3 -> (back to head) After inserting 0 at beginning: 0 -> 1 -> 2 -> 3 -> (back to head)
Complexity Analysis
Time: O(n) because we must traverse the list to find the last node
Space: O(1) because we only create one new node and use constant extra space
vs Alternative: Naive approach might rebuild the entire list or use extra arrays, which is less efficient; this method updates pointers directly in O(n) time
Edge Cases
empty list
new node points to itself and becomes head
DSA Go
if head == nil {
		newNode.next = newNode
		return newNode
	}
single node list
last node is the head itself, updated to point to new node
DSA Go
for last.next != head {
	last = last.next
}
When to Use This Pattern
When you see a problem asking to add a node at the start of a circular linked list, use this pattern to update the last node's pointer and reset the head to the new node to maintain the circle.
Common Mistakes
Mistake: Not updating the last node's next pointer to the new node, breaking the circular link
Fix: Always find the last node and set its next pointer to the new node after insertion
Summary
Inserts a new node at the start of a circular linked list while keeping it circular.
Use when you need to add elements quickly at the beginning of a circular linked list.
Remember to update the last node's next pointer to the new node to maintain the circle.

Practice

(1/5)
1. What happens when you insert a new node at the beginning of a circular linked list?
easy
A. The new node becomes the head and points to the old head, maintaining the circular link.
B. The new node is added at the end and does not affect the head.
C. The list breaks and becomes a linear linked list.
D. The new node replaces the last node in the list.

Solution

  1. Step 1: Understand the circular linked list structure

    A circular linked list has its last node pointing back to the head, forming a circle.
  2. Step 2: Insert new node at beginning

    The new node is linked to the current head, and the last node's next pointer is updated to this new node, making it the new head.
  3. Final Answer:

    The new node becomes the head and points to the old head, maintaining the circular link. -> Option A
  4. Quick Check:

    New head points to old head, circle intact = A [OK]
Hint: New head points to old head; last node points to new head [OK]
Common Mistakes:
  • Not updating last node's next pointer
  • Breaking the circular link
  • Adding node at end instead of beginning
2. Which of the following Go code snippets correctly inserts a new node at the beginning of a circular linked list?
easy
A. newNode.next = nil head = newNode
B. head.next = newNode newNode.next = head
C. newNode.next = head last.next = newNode head = newNode
D. last.next = head head = newNode newNode.next = last

Solution

  1. Step 1: Link new node to current head

    Assign newNode.next = head to point new node to the current head.
  2. Step 2: Update last node to point to new node and update head

    Set last.next = newNode to maintain circular link, then update head = newNode.
  3. Final Answer:

    newNode.next = head last.next = newNode head = newNode -> Option C
  4. Quick Check:

    Correct pointer updates = B [OK]
Hint: Link new node to head, update last node, then head [OK]
Common Mistakes:
  • Setting newNode.next to nil breaks circular link
  • Not updating last.next to new node
  • Incorrect order of pointer assignments
3. What will be the printed output of the circular linked list after inserting node with value 10 at the beginning, given the list initially contains 20 -> 30 -> 40 -> (back to 20)?
func printList(head *Node) {
    if head == nil {
        fmt.Println("List is empty")
        return
    }
    temp := head
    for {
        fmt.Printf("%d -> ", temp.data)
        temp = temp.next
        if temp == head {
            break
        }
    }
    fmt.Println("null")
}

// Insert 10 at beginning
newNode := &Node{data: 10}
// Assume last points to node with 40
newNode.next = head
last.next = newNode
head = newNode

printList(head)
medium
A. List is empty
B. 20 -> 30 -> 40 -> 10 -> null
C. 10 -> 20 -> 30 -> 40 -> 10 -> null
D. 10 -> 20 -> 30 -> 40 -> null

Solution

  1. Step 1: Insert new node 10 at beginning

    New node 10 points to old head 20, last node 40 points to new node 10, head updated to 10.
  2. Step 2: Print list starting from new head

    Traverse from 10: 10 -> 20 -> 30 -> 40, then stop at head again.
  3. Final Answer:

    10 -> 20 -> 30 -> 40 -> null -> Option D
  4. Quick Check:

    New head 10 followed by old nodes = A [OK]
Hint: New node prints first, then old nodes in order [OK]
Common Mistakes:
  • Printing extra node causing repeated values
  • Not updating last.next causing infinite loop
  • Confusing order of nodes after insertion
4. Given the following Go code to insert at beginning of a circular linked list, what is the error?
func insertAtBeginning(head *Node, data int) *Node {
    newNode := &Node{data: data}
    if head == nil {
        newNode.next = newNode
        return newNode
    }
    temp := head
    for temp.next != nil {
        temp = temp.next
    }
    newNode.next = head
    temp.next = newNode
    head = newNode
    return head
}
medium
A. The function should not return head.
B. The loop condition should check for temp.next != head, not nil.
C. head should not be updated inside the function.
D. newNode.next should be nil when list is empty.

Solution

  1. Step 1: Analyze loop condition for circular list

    In circular linked list, last node's next points to head, so loop should check temp.next != head, not nil.
  2. Step 2: Identify impact of wrong condition

    Checking temp.next != nil causes infinite loop or crash because next is never nil in circular list.
  3. Final Answer:

    The loop condition should check for temp.next != head, not nil. -> Option B
  4. Quick Check:

    Loop must stop at head, not nil [OK]
Hint: In circular list, last.next points to head, not nil [OK]
Common Mistakes:
  • Using nil instead of head in loop condition
  • Not updating head after insertion
  • Returning wrong pointer from function
5. You have a circular linked list with nodes 5 -> 15 -> 25 -> (back to 5). You want to insert a new node with value 1 at the beginning. After insertion, you want to print the list starting from the new head. Which sequence of pointer updates correctly achieves this without breaking the circular structure?
hard
A. Set newNode.next = head; find last node and set last.next = newNode; update head = newNode
B. Set newNode.next = nil; update head = newNode; last.next = head
C. Update head = newNode; set newNode.next = head; last.next = newNode
D. Set last.next = newNode; newNode.next = head; head = newNode.next

Solution

  1. Step 1: Link new node to current head

    Assign newNode.next = head so new node points to old head.
  2. Step 2: Update last node to point to new node and update head

    Find last node (with value 25) and set last.next = newNode to maintain circular link, then update head = newNode.
  3. Final Answer:

    Set newNode.next = head; find last node and set last.next = newNode; update head = newNode -> Option A
  4. Quick Check:

    New head points to old head; last points to new head [OK]
Hint: Link new node to head, last to new node, then update head [OK]
Common Mistakes:
  • Setting newNode.next to nil breaks circle
  • Updating head before linking nodes
  • Not updating last.next to new node
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard