From fa2232488933e21a9b548a9e1f51f6623ce5eb9f Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 12 Jul 2017 18:51:04 +0800 Subject: [PATCH] Remove Nth node from end of list Signed-off-by: begeekmyfriend --- 019_remove_nth_node_from_end_of_list/Makefile | 2 + .../remove_end.c | 58 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 019_remove_nth_node_from_end_of_list/Makefile create mode 100644 019_remove_nth_node_from_end_of_list/remove_end.c diff --git a/019_remove_nth_node_from_end_of_list/Makefile b/019_remove_nth_node_from_end_of_list/Makefile new file mode 100644 index 0000000..41a447c --- /dev/null +++ b/019_remove_nth_node_from_end_of_list/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test remove_end.c diff --git a/019_remove_nth_node_from_end_of_list/remove_end.c b/019_remove_nth_node_from_end_of_list/remove_end.c new file mode 100644 index 0000000..4c96721 --- /dev/null +++ b/019_remove_nth_node_from_end_of_list/remove_end.c @@ -0,0 +1,58 @@ +#include +#include + + struct ListNode { + int val; + struct ListNode *next; + }; + +struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { + struct ListNode *p, *prev, dummy; + if (n < 1) return NULL; + + dummy.next = head; + p = prev = &dummy; + while (n-- > 0) { + p = p->next; + } + + while (p->next != NULL) { + p = p->next; + prev = prev->next; + } + + struct ListNode *tmp = prev->next; + prev->next = tmp->next; + if (tmp == head) { + head = tmp->next; + } + free(tmp); + return head; +} + +int main(int argc, char **argv) +{ + int i; + struct ListNode *list, *p, *prev = NULL; + for (i = 1; i < argc; i++) { + p = malloc(sizeof(*p)); + p->val = atoi(argv[i]); + p->next = NULL; + if (i == 1) { + list = p; + } + if (prev != NULL) { + prev->next = p; + } + prev = p; + } + + list = removeNthFromEnd(list, 1); + if (list != NULL) { + for (p = list; p != NULL; p = p->next) { + printf("%d\n", p->val); + } + } + + return 0; +}