-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinkpop.c
More file actions
107 lines (90 loc) · 1.96 KB
/
linkpop.c
File metadata and controls
107 lines (90 loc) · 1.96 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* Linked list with push and pop
* September 16, 2021 */
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} node_t;
/* Print the linked list */
static void print_list(node_t *h) {
node_t *current;
for (current = h; current != NULL; current = current->next) {
printf("%x = %d\n", ¤t->val, current->val);
}
}
/* New push function, inserts at beginning instead of end */
static int push(node_t **h, int val) {
/* This **h is a double pointer */
if (*h == NULL) {
return 1;
}
node_t *new;
new = (node_t *)malloc(sizeof(node_t));
if (!new) {
return 1;
}
new->val = val;
new->next = *h;
/* append to the beginning, so make the old head the next of the new node */
*h = new;
return 0;
}
/* Remove from beginning of list, and return stored value */
static int pop(node_t **h) {
int ret = -1;
node_t *next = NULL;
if (*h == NULL) {
return ret;
}
next = (*h)->next;
ret = (*h)->val;
free(*h);
*h = next;
return ret;
}
int main(void) {
int p;
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 = 64;
head->next = (node_t *)malloc(sizeof(node_t));
if (!head->next) {
fprintf(stderr, "Could not allocate space for second node\n");
free(head);
return 1;
}
head->next->val = 42;
head->next->next = NULL;
printf("Here's the current list:\n");
print_list(head);
if (push(&head, 11) == 1) {
fprintf(stderr, "Could not push to linked list\n");
free(head->next);
free(head);
head = NULL;
return 1;
}
if (push(&head, 22) == 1) {
fprintf(stderr, "Could not push to linked list\n");
free(head->next->next);
free(head->next);
free(head);
head = NULL;
return 1;
}
printf("After two pushes:\n");
print_list(head);
p = pop(&head);
printf("Popped value %d\n", p);
p = pop(&head);
printf("Popped value %d\n", p);
free(head->next);
free(head);
head = NULL;
return 0;
}