My implementation of a C
doubly linked list doesn't seem to work correctly. I fear it may be due to my cursory knowledge of pointers in C
(coming from the blissful ignorance of interpreted languages). When I run this code, it seems print_list()
runs forever, even though it should be terminated by the next
field being NULL
.
#include<stdio.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
void print_list(Node* head) {
Node* cursor = head;
while(cursor != NULL) {
printf("data: %d\n", cursor->data);
cursor = cursor->next;
}
}
void push_node(Node* head, int data) {
Node node = {data, NULL, NULL};
Node* cursor = head;
while(cursor->next != NULL) {
cursor = cursor->next;
}
cursor->next = &node;
node.prev = cursor;
}
int main() {
Node root = {0, NULL, NULL};
push_node(&root, 1);
push_node(&root, 2);
print_list(&root);
return 0;
}
What am I doing wrong?? Any help would be much appreciated.