i trying insert node before given node. not able required output.
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* prev; struct node* next; }; void insert_beg(struct node** head, int new_data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = new_data; if(*head == null){ temp->next = *head; temp->prev = null; *head = temp; } else{ temp->next = *head; (*head)->prev = temp; *head = temp; } } void insert_before(struct node* next_node,int new_data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = new_data; if(next_node == null) printf("invalid!!!!"); temp->prev = next_node->prev; temp->next = next_node; next_node->prev = temp; if(temp->prev!=null) temp->prev->next = temp; } void printlist(struct node* head){ if(head == null) printf("the list empty\n"); else { while(head!=null){ printf("%d\n",head->data); head = head->next; } } } int main(){ struct node* head = null; printlist(head); insert_beg(&head,10); insert_beg(&head,20); insert_before(head,70); insert_beg(&head,30); printlist(head); }
here trying insert node(with data = 70) before 20.
output: 30,20,10
expected output: 30,70,20,10
when call insert_before
, if given node head, new node new head. need pass the address of head
in order modify it.
what have right looks this:
head | v ------ ------ ------ - 30 - ---> - 20 - ---> - 10 - ------ <--- ------ <--- ------ ^ ------ | - 70 - ---------| ------
to fix this, include address of head
in parameters insert_before
.
void insert_before(struct node **head, struct node *next_node, int new_data){ struct node* temp = malloc(sizeof(struct node)); // don't cast return value of malloc temp->data = new_data; if(next_node == null) printf("invalid!!!!"); temp->prev = next_node->prev; temp->next = next_node; next_node->prev = temp; if(temp->prev!=null) { temp->prev->next = temp; } else { *head = temp; } }
then call this:
insert_before(&head,head,70);
Comments
Post a Comment