Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Created Jul 4, 2021
Embed
What would you like to do?
CList insert at p
func InsertAtP(head **Node, p int, x int) {
if p < 1 {
fmt.Println("\nPositions start at 1. Invalid input position.")
return
}
if p == 1 {
InsertAtStart(head, x)
return
}
// If insertion point is not the start and the list is empty, insertion point is invalid.
if *head == nil {
fmt.Println("\nInvalid Position.")
return
}
current := *head
i := 1
for i < p-1 && current.Next != *head {
current = current.Next
i++
}
if i < p-1 {
fmt.Println("\nInvalid Position")
return
}
tmp := &Node{Data: x}
tmp.Next = tmp
fmt.Println("\nInserting", tmp, "at the position", p)
tmp.Next = current.Next
current.Next = tmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment