Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Last active June 30, 2021 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AahanSingh/6eebddb131bc5697c0f691868ae4bbab to your computer and use it in GitHub Desktop.
Save AahanSingh/6eebddb131bc5697c0f691868ae4bbab to your computer and use it in GitHub Desktop.
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