Files
C/leetcode/src/19.c
Mindaugas f0b38a3201 feat: remove nth node from end of list LeetCode (#1222)
* feat: remove nth node from end of list (leetcode #19)

* fix: update the leetcode #19 solution to introduce node pointing to head

---------

Co-authored-by: David Leal <halfpacho@gmail.com>
2023-03-03 09:12:04 -06:00

28 lines
565 B
C

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
struct ListNode entry, *p_free, *p = head;
int i, sz = 0;
entry.next = head;
while (p != NULL) {
p = p->next;
sz++;
}
for (i = 0, p = &entry; i < sz - n; i++, p = p -> next)
;
p_free = p->next;
if (n != 1) {
p->next = p->next->next;
} else {
p->next = NULL;
}
free(p_free);
return entry.next;
}