-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_explain.c
More file actions
71 lines (56 loc) · 1.43 KB
/
linked_list_explain.c
File metadata and controls
71 lines (56 loc) · 1.43 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
//linked lists
/*
---------- ----------
- Data - - Data -
---------- ----------
- Pointer- - - -> - Pointer-
---------- ----------
*/
//what the node struct needs to look like
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
struct node *root;
root = (struct node *) malloc( sizeof(struct node) );
root->next = 0;
root->x = 5;
}
//traversing the list
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
struct node *root;//this doesn't change or we lose the list in memory
struct node *conductor;//will point to each node as it traverses the list
root = malloc( sizeof(struct node) );
root->next = 0;
root->x = 12;
conductor = root;
if ( conductor != 0 ) {//iterates through each pointer via next until end is reached
while ( conductor->next != 0)
{
printf (" d\n", conductor->x)
conductor = conductor->next;
}
printf (" d\n", conductor->x)
}
conductor->next = malloc( sizeof(struct node) );//creates a node at end of list
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
//initialise new memory
conductor->next = 0;
conductor->x = 42;
return 0;
}