Делай как это ... Это соответствует твоим требованиям ...
void push(int number)
{
struct node *cur;
cur = first;
if(cur == NULL) //if it is first node
{
cur = (struct node*) malloc(sizeof(struct node));
cur->data = number;
cur->next = NULL;
cur->prev = cur;
first = cur;
return;
}
//note here Iam running the loop till cur->next!=NULL and not till cur != NULL. cur!=NULL makes the cur to act as head of a yet another new Linked List.
while (cur->next != NULL)
cur = cur->next;
(cur->next) = (struct node*) malloc(sizeof(struct node));
(cur->next)->data = number;
(cur->next)->next = NULL;
(cur->next)->prev = cur;
}
Или вы хотите сделать свою реализацию ....
Тогда ...
void push(int number)
{
struct node *cur;
cur = first;
if (cur != NULL) {
while (cur->next != NULL) {
cur = cur->next;
}
(cur->next) = (struct node *) malloc(sizeof(struct node));
(cur->next)->data = number;
(cur->next)->next = NULL;
(cur->next)->prev = cur;
}
else {/*Take action if it is a first node (if cur is NULL)*/}
}
Факты о вашем старом коде ..
void push(int number) {
struct node *cur;
cur = first;
if (cur != NULL) {
cur->prev = NULL;//no need. cur->prev must be NULL,already. since cur points to first.
//dont change cur->prev=someAddress it will change your head node
}
while (cur != NULL) {//flaw: run till cur->next!= NULL.Dont make cur NULL.
cur->prev = cur; //during iteration to last element no need of prev.
cur = cur->next;
}
//Do memory allocation,for cur->next and not for cur after this loop
cur->data = number; // change this to cur->next->data = number.
//initialize cur->next->prev,cur->next->next
if (cur->prev == NULL) {
first = cur;
}
//I can get your idea. But if you want to do this way,
//you have to use additional pointer like temp.
else {
cur->prev->next = cur;
}
}