-
-
Save AahanSingh/9deaeecd602b692502b98c939b55f246 to your computer and use it in GitHub Desktop.
Deleting an intermediate node.
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
// 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