kebria

Insertion at the end of a doubly linked list

Jun 16th, 2021
836
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Insertion at the end of a doubly linked list */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node {
  6.     struct node *prev;
  7.     int data;
  8.     struct node *next;
  9. };
  10.  
  11. struct node* addToEmpty(struct node* head, int data)
  12. {
  13.     struct node* temp = malloc(sizeof(struct node));
  14.  
  15.     temp->prev = NULL;
  16.     temp->data = data;
  17.     temp->next = NULL;
  18.  
  19.     head = temp;
  20.     return head;
  21. }
  22.  
  23. struct node* addAtBeg(struct node* head, int data)
  24. {
  25.     struct node* temp = malloc(sizeof(struct node));
  26.  
  27.     temp->prev = NULL;
  28.     temp->data = data;
  29.     temp->next = NULL;
  30.     temp->next = head;
  31.     head->prev = temp;
  32.  
  33.     head = temp;
  34.     return head;
  35. }
  36.  
  37. struct node* addAtEnd(struct node* head, int data)
  38. {
  39.     struct node *temp, *tp;
  40.     temp = malloc(sizeof(struct node));
  41.  
  42.     temp->prev = NULL;
  43.     temp->data = data;
  44.     temp->next = NULL;
  45.  
  46.     tp = head;
  47.     while (tp->next != NULL)
  48.     {
  49.         tp = tp->next;
  50.     }
  51.     tp->next = temp;
  52.     temp->prev = tp;
  53.     return head;
  54. }
  55.  
  56. int main()
  57. {
  58.     struct node* head = NULL;
  59.     struct node* ptr;
  60.     head = addToEmpty(head, 45);
  61.     head = addAtBeg(head, 25);
  62.     head = addAtEnd(head, 90);
  63.  
  64.     ptr = head;
  65.     while (ptr != NULL)
  66.     {
  67.         printf("%d ", ptr->data);
  68.         ptr = ptr->next;
  69.     }
  70.     return 0;
  71. }
  72.  
  73. /* Ouptut: 25 45 90 */
RAW Paste Data