Skip to content

Instantly share code, notes, and snippets.

@mumunuu
Created February 28, 2021 14:01
Show Gist options
  • Save mumunuu/2cc3fc6c39a5682d83fceff6cf0c04b9 to your computer and use it in GitHub Desktop.
Save mumunuu/2cc3fc6c39a5682d83fceff6cf0c04b9 to your computer and use it in GitHub Desktop.
algorithm(leetcode) Remove Nth Node From End of List
func removeNthFromEnd(head *ListNode, n int) *ListNode {
head = &ListNode{Next: head}
cur, curN := head, head
//head.Next == cur.Next => true
//cur.Next == curN.Next => true
for i := 0; cur != nil; i++ {
curN = curN.Next
cur = cur.Next
if i == n {
/*
n갯수만큼 돌다가 다시 초기화해주면,
for문이 다 돌았을 때 해당 curN은 삭제할 인덱스 바로 직전에 위치함
*/
curN = head
}
}
curN.Next = curN.Next.Next //두번 건너뛰면 삭제할 수 있음
return head.Next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment