-
Notifications
You must be signed in to change notification settings - Fork 0
/
19_remove_nth_from_end.c
56 lines (52 loc) · 1.1 KB
/
19_remove_nth_from_end.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Copyright (C) 2016 Leonard Ding <dingxiaoyun88@gmail.com> */
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(head == NULL){
return NULL;
}
struct ListNode* h1;
struct ListNode* h2;
h1 = h2 = head;
int i = 0;
for(i = 0; i < n; i++){
h1 = h1->next;
}
if(h1 == NULL){
head = head->next;
free(h2);
} else {
while(h1->next != NULL){
h1 = h1->next;
h2 = h2->next;
}
if(n == 1){
h2->next = NULL;
free(h1);
} else {
struct ListNode* tmp = h2->next;
h2->next = tmp->next;
free(tmp);
}
}
return head;
}
int main(){
struct ListNode* h1 = malloc(sizeof(struct ListNode* ));
h1->next = NULL;
removeNthFromEnd(h1, 1);
return 0;
}