fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct node{
  5. int data;
  6. struct node *prev;
  7. struct node *next;
  8. };
  9.  
  10. struct node* createNode()
  11. {
  12. struct node* temp=(struct node*)malloc(sizeof(struct node));
  13. if(!temp)
  14. return NULL;
  15. else
  16. return temp;
  17. }
  18.  
  19. void insertAtBeg(struct node** head,int item)
  20. {
  21. struct node *temp=createNode();
  22. temp->data=item;
  23. temp->prev=NULL;
  24. if(*head==NULL)
  25. {
  26. temp->next=NULL;
  27. }
  28.  
  29. else
  30. {
  31. temp->next=*head;
  32. (*head)->prev=temp;
  33. }
  34. (*head)=temp;
  35. }
  36.  
  37. void insertAtEnd(struct node** head,int item)
  38. {
  39.  
  40. struct node *temp=createNode();
  41. temp->data=item;
  42. temp->next=NULL;
  43. if(*head==NULL)
  44. {
  45. temp->prev=NULL;
  46. }
  47. else
  48. {
  49. struct node* prev_node=*head;
  50. while(prev_node->next!=NULL)
  51. {
  52. prev_node=prev_node->next;
  53. }
  54. temp->prev=prev_node;
  55. prev_node->next=temp;
  56. }
  57. }
  58.  
  59. void insertAtMiddle(struct node** head,int item)
  60. {
  61. struct node *temp=createNode();
  62. temp->data=item;
  63. if(*head==NULL)
  64. {
  65. temp->prev=NULL;
  66. temp->next=NULL;
  67. *head=temp;
  68. }
  69.  
  70. else
  71. {
  72. int n;
  73. printf("Enter data after which node is to be inserted :");
  74. scanf("%d",&n);
  75. struct node *prev_node=*head;
  76. while(prev_node->next!=NULL)
  77. {
  78. if(prev_node->data==n)
  79. {
  80. temp->next=prev_node->next;
  81. prev_node->next->prev=temp;
  82. temp->prev=prev_node;
  83. prev_node->next=temp;
  84. }
  85. prev_node=prev_node->next;
  86. }
  87. }
  88. }
  89.  
  90. void display(struct node* head)
  91. {
  92. while(head!=NULL)
  93. {
  94. printf("%d ",head->data);
  95. head=head->next;
  96. }
  97. }
  98.  
  99. int main(void)
  100. {
  101. struct node* head=NULL;
  102. insertAtBeg(&head,20);
  103. display(head);
  104. insertAtBeg(&head,10);
  105. display(head);
  106. insertAtEnd(&head,30);
  107. display(head);
  108. insertAtEnd(&head,40);
  109. display(head);
  110. insertAtMiddle(&head,25);
  111. display(head);
  112. return 0;
  113. }
Success #stdin #stdout 0s 2292KB
stdin
20
stdout
20 10 20 10 20 30 10 20 30 40 Enter data after which node is to be inserted :10 20 25 30 40