[<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
 Решения упражнений
                           Связанный список

slinked.c:
 1 /*
 2  * This program illustrates a singly linked list that is
 3  * dynamically growing.
 4  */
 5
 6 #include <sys/types.h>
 7 #include <stdlib.h>
 8 #include <stdio.h>
 9 #include <string.h>
10
11 struct node {
12     char *data;
13     struct node* next;
14 };
15
16 main()
17 {
18     char line[BUFSIZ];
19     struct node *head, *here, *p, *create(char *);
20
21     /* initialize the linked list with a dummy node */
22     head = malloc(sizeof(struct node));
23     head->next = NULL;
24     here = head;
25
26     /* get a line of input and append it to the linked list */
27     printf("Enter lines of text:\n");
28     while (gets(line) != NULL) {
29         if (line[0] == '.')
30             break;
31         here->next = create(line);
32         here = here->next;
33     }
34
35     /* print out the lines in the linked list */
36     for (p = head->next; p != NULL; p = p->next)
37         puts(p->data);
38 }
39
40
41 /*
42  * this function creates a node
43  */
44
45 struct node *create(char *input)
46 {
47     struct node *q;
48
49     q = malloc(sizeof(struct node));
50     q->data = malloc(strlen(input) + 1);
51     strcpy(q->data, input);
52     q->next = NULL;
53     return(q);
54 }