-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
89 lines (79 loc) · 1.28 KB
/
list.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
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int val;
struct node *next;
} * Node;
void print_list(Node head)
{
Node current = head;
printf("The list contains:\n");
while (current != NULL)
{
printf("[%d]", current->val);
current = current->next;
}
printf("\n");
}
Node createNode(int e)
{
Node new_node = (Node)malloc(sizeof(Node));
new_node->val = e;
new_node->next = NULL;
return new_node;
}
int append(Node *head, int e)
{
if (*head == NULL)
{
*head = createNode(e);
}
else
{
Node current = *head;
while (current->next != NULL)
{
current = current->next;
}
current->next = createNode(e);
}
return 1;
}
int prepend(Node *head, int e)
{
if (*head == NULL)
{
*head = createNode(e);
}
else
{
Node new_node = createNode(e);
new_node->next = *head;
*head = new_node;
}
return 1;
}
int fill_list(Node *head)
{
int i = 0;
char input;
input = getchar();
while (input != 'Q')
{
if (input != '\n')
{
i += prepend(head, atoi(&input));
}
input = getchar();
}
return i;
}
int main()
{
printf("\nAdd values to list. Press Q + Enter to stop\n");
Node head = NULL;
printf("\n%d values added\n", fill_list(&head));
print_list(head);
return 1;
}