Advertisement
kebria

Insertion at the beginning. Circular doubly linked list

Jun 20th, 2021
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. /* Insertion at the beginning. Circular 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(int data)
  12. {
  13.     struct node* temp = malloc(sizeof(struct node));
  14.     temp->prev = temp;
  15.     temp->data = data;
  16.     temp->next = temp;
  17.     return temp;
  18. }
  19.  
  20. struct node* addAtBeg(struct node* tail, int data)
  21. {
  22.     struct node *newP = addToEmpty(data);
  23.     if (tail == NULL)
  24.         return newP;
  25.     else
  26.     {
  27.         struct node *temp = tail->next;
  28.  
  29.         newP->prev = tail;
  30.         newP->next = temp;
  31.         temp->prev = newP;
  32.         tail->next = newP;
  33.         return tail;
  34.     }
  35. }
  36.  
  37. void print(struct node* tail)
  38. {
  39.     if (tail == NULL)
  40.         printf("No element in the list\n");
  41.     else
  42.     {
  43.         struct node *temp = tail->next;
  44.         do {
  45.             printf("%d ", temp->data);
  46.             temp = temp->next;
  47.         } while (temp != tail->next);
  48.     }
  49.     printf("\n");
  50. }
  51.  
  52. int main()
  53. {
  54.     struct node* tail = NULL;
  55.     tail = addToEmpty(45);
  56.     tail = addAtBeg(tail, 34);
  57.     print(tail);
  58.     return 0;
  59. }
  60.  
  61. //Output: 34 45
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement