go: add «19. Remove Nth Node From End of List»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
f0cdb67ac1
commit
a2bebb36df
1 changed files with 29 additions and 0 deletions
29
go/remove-nth-node-from-end-of-list.go
Normal file
29
go/remove-nth-node-from-end-of-list.go
Normal 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
|
||||||
|
}
|
Loading…
Reference in a new issue