- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path19.c
73 lines (56 loc) · 1.42 KB
/
19.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
63
64
65
66
67
68
69
70
71
72
73
#include<stdio.h>
#include<stdlib.h>
structListNode {
intval;
structListNode*next;
};
structListNode*removeNthFromEnd(structListNode*head, intn) {
if (n==0) returnhead;
structListNode*fast, *slow;
fast=slow=head;
while (n--) {
fast=fast->next;
}
if (fast==NULL) { /* reach the tail, so we delete the head */
head=head->next;
returnhead;
}
while (fast->next!=NULL) {
fast=fast->next;
slow=slow->next;
}
/* slow pointer is at the previous node of the one to be deleted */
slow->next=slow->next->next;
returnhead;
}
intmain() {
structListNode*l1= (structListNode*)calloc(5, sizeof(structListNode));
structListNode*p=l1;
inti;
for (i=1; i <= 4; i++) {
p->val=i;
p->next=p+1;
p++;
}
p->val=5;
p->next=NULL;
p=removeNthFromEnd(l1, 1); /* delete the tail */
while (p) {
printf("%d ", p->val);
p=p->next;
}
printf("\n");
p=removeNthFromEnd(l1, 0); /* delete nothing */
while (p) {
printf("%d ", p->val);
p=p->next;
}
printf("\n");
p=removeNthFromEnd(l1, 4); /* delete the head */
while (p) {
printf("%d ", p->val);
p=p->next;
}
printf("\n");
return0;
}