-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_build.c
62 lines (47 loc) · 1.1 KB
/
list_build.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
/* simple list building with malloc
to illustrate dynamic memory allocatio
in C */
#include <stdio.h>
#include <stdlib.h>
struct listrec {
int value;
struct listrec *next;
} ;
// prototype declarations
struct listrec *build_list (void);
void visit_list (struct listrec *listptr);
struct listrec *build_list (void) {
struct listrec *liststart = NULL,*listend,*newentry;
int val;
while (scanf ("%d",&val) == 1 ) {
newentry= malloc (sizeof (struct listrec));
if (newentry == NULL) {
printf("malloc failed: \n");
exit(EXIT_FAILURE);
}
if (liststart == NULL)
/* first entry in list */
liststart=listend=newentry;
else {
/* link new entry into list */
listend->next = newentry;
listend = newentry;
}
listend->value = val;
}
listend->next=NULL;
return (liststart);
}
void visit_list(struct listrec *listptr)
{
while(listptr != NULL) {
printf("%d\n",listptr -> value);
listptr = listptr -> next;
} }
int main ()
{
struct listrec *liststart;
liststart=build_list ();
visit_list (liststart);
return(0);
}