-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19.RemoveNthNodeFromEndofList.c
More file actions
78 lines (67 loc) · 1.31 KB
/
19.RemoveNthNodeFromEndofList.c
File metadata and controls
78 lines (67 loc) · 1.31 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* Definition for singly-linked list.
*/
struct _ListNode {
int val;
struct _ListNode *next;
};
typedef struct _ListNode ListNode;
void removeNthFromEnd(ListNode* head, int n) {
ListNode* p1 = head, * p2 = head;
int i;
for (i = 0; i < n+1; i++) {
if (p1) {
p1 = p1->next;
}
}
while (p1) {
p1 = p1->next;
p2 = p2->next;
}
printf("p2->val: %d\n", p2->val);
p2->next = p2->next->next;
return;
}
int main()
{
ListNode* l1 = NULL;
ListNode* p1 = l1;
int i = 0;
for (i = 0; i < 5; i++)
{
ListNode* node = malloc(sizeof(ListNode));
node->val = i + 1;
node->next = NULL;
if (p1 == NULL) {
p1 = l1 = node;
} else {
p1->next = node;
p1 = p1->next;
}
}
printf("print l1:\n\t");
p1 = l1;
while (p1) {
printf("%d ", p1->val);
p1 = p1->next;
}
printf("\n");
removeNthFromEnd(l1, 2);
printf("print l1:\n\t");
p1 = l1;
while (p1) {
printf("%d ", p1->val);
p1 = p1->next;
}
printf("\n");
}