-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove_nth_node_LL.c
62 lines (51 loc) · 1005 Bytes
/
remove_nth_node_LL.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
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
struct ListNode *next;
};
static inline int numberofListNodes(struct ListNode* head)
{
if(!head)
{
return -1;
}
struct ListNode* tmp = head;
int count = 0;
while(tmp != NULL)
{
count++;
tmp = tmp->next;
}
return count;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
if(!head || !n || n < 0)
{
return NULL;
}
struct ListNode* tmp = head;
int N = numberofListNodes(head);
if(N == -1)
{
return NULL;
}
if(n == N)
{
head = head->next;
return head;
}
for(int i = 1; i < N-n; i++)
{
tmp = tmp->next;
}
if(n == 1)
{
tmp->next = NULL;
return head;
}
tmp->next = tmp->next->next;
return head;
}