Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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