Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Last active July 3, 2021 12:36
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/77fb7fdd8f103abd45ed3a52d1a15542 to your computer and use it in GitHub Desktop.
Save AahanSingh/77fb7fdd8f103abd45ed3a52d1a15542 to your computer and use it in GitHub Desktop.
DLList InsertAtP
func InsertAtP(head **DLNode, p int, x int) {
if p < 1 {
fmt.Println("Positions start at 1. Invalid Position.")
return
}
if p == 1 {
InsertAtStart(head, x)
return
}
if *head == nil {
fmt.Println("Position Invalid.")
return
}
current := *head
i := 1
// Find the penultimate node
for i < p-1 && current.Next != nil {
current = current.Next
i++
}
// This means we reached the end of the list and i != p-1
if i < p-1 {
fmt.Println("Invalid Position")
return
}
tmp := &DLNode{Data: x}
fmt.Println("Inserting", tmp, "at position", p)
tmp.Prev = current
tmp.Next = current.Next
if current.Next != nil {
current.Next.Prev = tmp
}
current.Next = tmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment