-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinkpush.c
More file actions
64 lines (53 loc) · 1.31 KB
/
linkpush.c
File metadata and controls
64 lines (53 loc) · 1.31 KB
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
/* Linked list with push
* September 15, 2021 */
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} node_t;
static void print_list(node_t *h) {
node_t *current = h;
while (current != NULL) {
printf("%x = %d\n", ¤t->val, current->val); // print address of value and value
current = current->next; // advance to next item
}
}
/* Push a node to the end of the list with value val */
static void push(node_t *h, int v) {
node_t *current = h;
while (current->next != NULL)
current = current->next;
/* Allocate space for newly added node */
current->next = (node_t *)malloc(sizeof(node_t));
current->next->val = v;
current->next->next = NULL;
}
int main(void) {
node_t *head = NULL;
head = (node_t *)malloc(sizeof(node_t));
if (!head) {
fprintf(stderr, "Could not allocate space for first node\n");
return 1;
}
head->val = 1;
head->next = (node_t *)malloc(sizeof(node_t));
if (!head->next) {
fprintf(stderr, "Could not allocate space for second node\n");
free(head);
head = NULL;
return 1;
}
head->next->val = 2;
head->next->next = NULL;
printf("Here's the current list: \n");
print_list(head);
push(head, 5);
printf("Updated linked list: \n");
print_list(head);
free(head->next->next);
free(head->next);
free(head);
head = NULL;
return 0;
}