Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Created July 4, 2021 05:07
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/ea1a82b6dbb09aa839289801461223ed to your computer and use it in GitHub Desktop.
Save AahanSingh/ea1a82b6dbb09aa839289801461223ed to your computer and use it in GitHub Desktop.
DL List delete at specific position
func DeleteAtP(head **DLNode, p int) {
// Edge case 1: Positions less than 1
if p < 1 {
fmt.Println("Positions start from 1. Position Invaid.")
return
}
// Edge case 2: List is empty
if *head == nil {
fmt.Println("List empty")
return
}
// Edge case 3: Deletion position is 1
if p == 1 {
DeleteFirst(head)
return
}
current := *head
i := 1
// Find node to delete
for i < p && current.Next != nil {
current = current.Next
i++
}
// Edge case 4: Position exceeds length of the list
if i < p {
fmt.Println("Position Invalid")
return
}
previousNode := current.Prev
nextNode := current.Next
previousNode.Next = nextNode
// Edge case 5: The node to delete is the last in the list. If it is nextNode will be nil
if nextNode != nil {
nextNode.Prev = previousNode
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment