-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.16-print-longest-line.c
79 lines (66 loc) · 1.48 KB
/
1.16-print-longest-line.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
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
const int BUFSIZE = 2;
struct List {
struct List *next;
char *buf;
};
void unwrap(struct List *first) {
while (true) {
assert(first != NULL);
for (int i = 0; i < BUFSIZE; i++) {
char c = first->buf[i];
if (c == EOF) {
return;
}
putchar(c);
}
first = first->next;
}
}
int longest(struct List *first, struct List *last, int cur, int max) {
struct List list;
if (first == NULL) {
assert(last == NULL);
assert(cur == 0);
last = first = &list;
} else {
assert(last != NULL);
assert(cur != 0);
last = last->next = &list;
}
char buf[BUFSIZE];
list.buf = buf;
for (int i = 0; i < BUFSIZE; i++) {
char c = getchar();
if (c == EOF) {
if (cur > max) {
buf[i] = c;
putchar('\r');
unwrap(first);
}
return -1;
}
if (c == '\n') {
if (cur > max) {
max = cur;
buf[i] = EOF;
putchar('\r');
unwrap(first);
}
return max;
}
buf[i] = c;
cur++;
}
return longest(first, last, cur, max);
}
int main() {
int max = 0;
while (max != -1) {
max = longest(NULL, NULL, 0, max);
}
putchar('\n');
return 0;
}