-
-
Save AahanSingh/77fb7fdd8f103abd45ed3a52d1a15542 to your computer and use it in GitHub Desktop.
DLList InsertAtP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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