Systemnahe Programmierung in C: Abstraktion mit Funktionen |
1#include <stdio.h>
2
3typedef unsigned int Element;
4
5typedef struct node *List;
6
7struct node
8{
9 Element info;
10 List next;
11};
12
13/* ---------------------------------------- */
14
15#define isEmpty(l) (l == (List)0)
16
17void
18print (List l)
19{
20 while (!isEmpty (l))
21 {
22 printf ("%u\n", l->info);
23 l = l->next;
24 }
25}
26
27unsigned
28length (List l)
29{
30 unsigned res = 0;
31
32 while (!isEmpty (l))
33 {
34 ++res;
35 l = l->next;
36 }
37 return res;
38}
39
40Element
41maximum (List l)
42{
43 Element res = l->info;
44
45 while (!isEmpty (l))
46 {
47 if (res < l->info)
48 {
49 res = l->info;
50 }
51 l = l->next;
52 }
53
54 return res;
55}
56
57/* ---------------------------------------- */
58
59typedef void (*Process) (Element e);
60
61void
62forall (List l, Process p)
63{
64 while (!isEmpty (l))
65 {
66 p (l->info);
67 l = l->next;
68 }
69}
70
71/* ---------------------------------------- */
72
73static void
74printElement (Element e)
75{
76 printf ("%u\n", e);
77}
78
79void
80print2 (List l)
81{
82 forall (l, printElement);
83}
84
85/* ---------------------------------------- */
86
87static unsigned listLength;
88static void
89incrLength (Element e)
90{
91 ++listLength;
92}
93
94unsigned
95length2 (List l)
96{
97 listLength = 0;
98 forall (l, incrLength);
99 return listLength;
100}
101
102/* ---------------------------------------- */
103
104static Element maximumInList;
105
106static void
107maxElement (Element e)
108{
109 if (maximumInList < e)
110 maximumInList = e;
111}
112
113Element
114maximum2 (List l)
115{
116 maximumInList = l->info;
117 forall (l, maxElement);
118 return maximumInList;
119}
|
Letzte Änderung: 11.01.2007 | © Prof. Dr. Uwe Schmidt |