-
Notifications
You must be signed in to change notification settings - Fork 0
/
q1.c
132 lines (113 loc) · 1.88 KB
/
q1.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//
// Delete k-th element in the one-way list
//
// C-only
//
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 7
struct Node
{
struct Node *next;
int n;
// ...
};
//
// k = 0, 1, 2 ...
//
int deleteK(struct Node **pptr, unsigned int k)
{
if ((*pptr) == NULL)
{
return -1;
}
if (k == 0)
{
struct Node *tmp = (*pptr);
(*pptr) = (*pptr)->next;
free(tmp);
return 0;
}
struct Node *p = (*pptr), *prev;
for(unsigned int i = 0; (i < k) && (p != NULL); i++, prev = p, p = p->next)
{
if (p->next == NULL)
{
return -1; // size is less than k
}
}
if (p != NULL)
{
prev->next = p->next;
free(p);
}
else
{
return -2; // unexpected
}
return 0;
}
void freeList(struct Node *ptr)
{
struct Node *tmp;
while (ptr)
{
tmp = ptr;
ptr = ptr->next;
free(tmp);
}
}
void printList(struct Node *ptr)
{
for(struct Node *tmp = ptr; tmp != NULL; tmp = tmp->next)
{
printf("%d ", tmp->n);
}
printf("\n");
}
int main(int argc, char ** argv)
{
if (argc < 2)
{
printf("Usage: q1 <number>\n");
return 0;
}
int k = atoi(argv[1]);
if (k < 0)
{
printf("Argument should be positive.\n");
return 0;
}
struct Node * const ptr = malloc(sizeof(struct Node));
if (ptr)
{
struct Node *p = ptr;
for (int i = 0; i < MAXLEN; i++ && p != NULL, p = p->next)
{
p->n = i;
if (i < MAXLEN - 1)
{
p->next = malloc(sizeof(struct Node));
if(p->next == NULL)
{
freeList(ptr);
return -1;
}
}
else
{
p->next = NULL;
}
}
struct Node *pp = ptr;
printList(pp);
if (deleteK(&pp, k))
{
printf("Nothing was deleted.\n");
}
printList(pp);
freeList(pp);
}
return 0;
}