Skip to content

Commit

Permalink
Remove Nth node from end of list
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 12, 2017
1 parent 3b530e7 commit fa22324
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 019_remove_nth_node_from_end_of_list/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test remove_end.c
58 changes: 58 additions & 0 deletions 019_remove_nth_node_from_end_of_list/remove_end.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#include <stdio.h>
#include <stdlib.h>

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;
}

0 comments on commit fa22324

Please sign in to comment.