Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Last active Jul 3, 2021
Embed
What would you like to do?
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