Created
December 15, 2022 23:32
-
-
Save abdulrahmanAlotaibi/925855307d1887254fff1e11e28d6cfb to your computer and use it in GitHub Desktop.
Linkedlist: Remove Nth Node From End of List
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
/** | |
* Definition for singly-linked list. | |
* type ListNode struct { | |
* Val int | |
* Next *ListNode | |
* } | |
*/ | |
func removeNthFromEnd(head *ListNode, n int) *ListNode { | |
dummy := &ListNode{} | |
dummy.Next = head | |
first := head | |
var length int | |
for first != nil { | |
length++ | |
first = first.Next | |
} | |
length -= n | |
first = dummy | |
// Stop before the node we want to delete | |
for length > 0 { | |
first = first.Next | |
length-- | |
} | |
first.Next = first.Next.Next | |
return dummy.Next | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment