Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Insert node at position p
func InsertAtP(head **Node, p int, x int) {
if p < 1 {
fmt.Println("Positions start at 1")
return
}
tmp := Node{Data: x, Next: nil}
if p == 1 {
fmt.Println("\nInserting", tmp, "at the position", p)
tmp.Next = *head
*head = &tmp
return
}
if *head == nil {
fmt.Println("Invalid Position")
return
}
current := *head
i := 1
for i < p-1 && current.Next != nil {
current = current.Next
i++
}
if i < p-1 {
fmt.Println("Invalid Position")
return
}
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