Skip to content

Instantly share code, notes, and snippets.

@AahanSingh
Last active June 30, 2021 16:13
Show Gist options
  • Save AahanSingh/9deaeecd602b692502b98c939b55f246 to your computer and use it in GitHub Desktop.
Save AahanSingh/9deaeecd602b692502b98c939b55f246 to your computer and use it in GitHub Desktop.
Deleting an intermediate node.
// DeleteAtP deletes the node located at index location 'p'.
// Deletion is inplace.
func DeleteAtP(head **Node, p int) {
if p == 0 {
fmt.Println("\nPositions start from 1. Cannot delete.")
return
}
if *head == nil {
fmt.Println("\nList is empty")
}
// First node will be deleted
if p == 1 {
fmt.Println("\nDeleting Node: ", **head, "at position", p)
*head = (*head).Next
return
}
i := 1
previous := &Node{}
current := *head
for current != nil && i < p {
previous = current
current = current.Next
i++
}
if current == nil {
fmt.Println("\nPosition does not exist")
return
}
fmt.Println("\nDeleting Node: ", *current, "at position", p)
previous.Next = current.Next
current = nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment