diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 4c124798..1ae9af3a 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -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 | diff --git a/leetcode/src/19.c b/leetcode/src/19.c new file mode 100644 index 00000000..c189f8f2 --- /dev/null +++ b/leetcode/src/19.c @@ -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; +}