go: add «19. Remove Nth Node From End of List»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-03-03 20:51:00 +01:00
parent f0cdb67ac1
commit a2bebb36df
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,29 @@
package remove_nth_node_from_end_of_list
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(lst *ListNode, n int) *ListNode {
toRemove := lst
head := lst
for i := 0; i < n; i++ {
head = head.Next
}
if head == nil {
return toRemove.Next
}
for head.Next != nil {
toRemove = toRemove.Next
head = head.Next
}
toRemove.Next = toRemove.Next.Next
return lst
}