forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
3b530e7
commit fa22324
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test remove_end.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |