mirror of
https://github.com/TheAlgorithms/C.git
synced 2026-07-22 17:02:52 +00:00
* 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>
28 lines
565 B
C
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;
|
|
}
|