This is the code for a doubly linked list where the values are inserted at the beginning. The code keeps returning the head values instead of the actual values.
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;
void InsertatBegin(int a){
struct Node* NewNode = (struct Node*)(malloc(sizeof(struct Node*)));
NewNode->data = a;
NewNode->next = NULL;
NewNode->prev = NULL;
if (head == NULL){
head = NewNode;
return;
}
NewNode->next = head;
head->prev = NewNode;
head = NewNode;
}
void traverse(){
struct Node* temp = head;
while (temp != NULL) {
if (temp->next == NULL) {
printf(" %d->NULL", temp->data);
}
else {
printf(" %d->", temp->data);
}
temp = temp->next; // Traversing the List till end
}
printf("\n");
}
int main(){
head = NULL;
InsertatBegin(5);
InsertatBegin(6);
InsertatBegin(7);
InsertatBegin(8);
InsertatBegin(9);
traverse();
}
This is the output for the code, it seems to print the address of the nodes instead of the values stored in the Node.data structure.
Output:
752904464-> 752904448-> 752904432-> 752904416-> 5->NULL
