Hey guys,
my list is NULL in the beginning.
do I have to make a special case for when inserting the first element of the doubly linked list? I am having trouble with pointing to the previous element when adding the first element.
Code:
#include <stdio.h>
#include <stdlib.h>
/*prototypes*/
int push(struct node**, int);
int printList(struct node*);
/*doubly linked-list structure*/
struct node {
int data;
struct node* nextPtr;
struct node* previousPtr;
struct node* childPtr; /*will point to another list*/
};
/*main*/
int main(void){
struct node* head = NULL;
int m = 5;
push(&head, m);
printList(head);
free(head); /*hehe, ya I know*/
return 0;
}
int push(struct node** head, int data){
struct node* current = *head;
struct node* newNode;
if( !(newNode = malloc(sizeof(struct node))) )
return -1;
newNode->data = data;
newNode->nextPtr = *head;
newNode->previousPtr = NULL;
/* I tried (*head)->previousPtr = newNode here but the program crashes.
*I think its because *head is NULL here*/
*head = newNode;
return 0;
}
int printList(struct node* head){
while(head != NULL){
printf("%d ", head->data);
head = head->nextPtr;
}
printf("\n");
return 0;
}
So yeah, my question is do I need to make a special case for inserting the first element in a doubly linked list, or is there a way around it?
Thanks!
PS -- I havent done all the error handling etc yet. I usually do that at the end.