Skip to content

Commit f0b38a3

Browse files
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 <[email protected]>
1 parent f141ae4 commit f0b38a3

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

leetcode/DIRECTORY.md

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

leetcode/src/19.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* struct ListNode *next;
6+
* };
7+
*/
8+
9+
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
10+
struct ListNode entry, *p_free, *p = head;
11+
int i, sz = 0;
12+
entry.next = head;
13+
while (p != NULL) {
14+
p = p->next;
15+
sz++;
16+
}
17+
for (i = 0, p = &entry; i < sz - n; i++, p = p -> next)
18+
;
19+
p_free = p->next;
20+
if (n != 1) {
21+
p->next = p->next->next;
22+
} else {
23+
p->next = NULL;
24+
}
25+
free(p_free);
26+
return entry.next;
27+
}

0 commit comments

Comments
 (0)