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>
This commit is contained in:
Mindaugas 2023-03-03 15:12:04 +00:00 committed by GitHub
parent f141ae4166
commit f0b38a3201
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 0 deletions

View File

@ -21,6 +21,7 @@
| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix) | [C](./src/14.c) | Easy |
| 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest) | [C](./src/16.c) | Medium |
| 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number) | [C](./src/17.c) | Medium |
| 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list) | [C](./src/19.c) | Medium |
| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses) | [C](./src/20.c) | Easy |
| 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists) | [C](./src/21.c) | Easy |
| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs) | [C](./src/24.c) | Medium |

27
leetcode/src/19.c Normal file
View File

@ -0,0 +1,27 @@
/**
* 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;
}