-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list.c
53 lines (44 loc) · 959 Bytes
/
linked_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
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int number;
struct node *next;
}
node;
//prototypes
void addNode(int num);
void printList();
void freeMemory();
//declaring list as global variable
node *list = NULL;
int main(void){
addNode(1);
addNode(2);
addNode(3);
addNode(4);
printList();
freeMemory();
return 0;
}
//this function will add a new node to the beginning of the linked list
void addNode(int num){
node *n = malloc(sizeof(node));
if(n == NULL) return;
n -> number = num; //same as *n.number = num;
n -> next = list;
list = n;
}
void printList(){
for (node *i = list; i != NULL; i = i -> next){
printf("number in node is %i\n",i -> number);
}
}
//free all nodes one by one
void freeMemory(){
while(list != NULL){
node *tmp = list -> next;
printf("freeing node %i\n",list -> number);
free(list);
list = tmp;
}
}