193030

Linked list displaying, sum

Aug 31st, 2020
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct Node {
  4.     int data;
  5.     struct Node* next;
  6. }* first = NULL;
  7.  
  8. int count = 0;
  9. void create(int A[], int n)
  10. {
  11.     int i;
  12.     struct Node *t, *last;
  13.     first = (struct Node*)malloc(sizeof(struct Node));
  14.     first->data = A[0];
  15.     first->next = NULL;
  16.     last = first;
  17.     for (i = 1; i < n; i++) {
  18.         t = (struct Node*)malloc(sizeof(struct Node));
  19.         t->data = A[i];
  20.         t->next = NULL;
  21.         last->next = t;
  22.         last = t;
  23.     }
  24. }
  25. void Display(struct Node* p)
  26. {
  27.     while (p != NULL) {
  28.         printf("%d ", p->data);
  29.         p = p->next;
  30.     }
  31. }
  32. void LinkedListDisplay(struct Node* p)
  33. {
  34.     if(p!=NULL)
  35.     {
  36.         printf("%d", p->data);
  37.         LinkedListDisplay(p->next);
  38.     }
  39.  
  40. }
  41.  
  42. void LinkedListDisplayReverse(struct Node* p)
  43. {
  44.  
  45.     if(p!=NULL)
  46.     {
  47.         LinkedListDisplayReverse(p->next);
  48.         printf("%d ", p->data);
  49.  
  50.     }
  51.  
  52.  
  53. }
  54.  
  55. void LinkedListCount(struct Node* p)
  56. {
  57.     if(p!=NULL)
  58.     {
  59.         count++;
  60.         LinkedListCount(p->next);
  61.     }
  62.     else
  63.         printf("The number of elements in the linked list is: %d ", count);
  64. }
  65.  
  66. void LinkedListSum(struct Node *p)
  67. {
  68.     int sum = 0;
  69.     while(p)
  70.     {
  71.         sum +=p->data;
  72.         p = p->next;
  73.     }
  74.     printf("\n The of the linked list is: %d", sum);
  75. }
  76.  
  77. /* Ne raboti
  78. void LinkedListImprovedSearch(Node *p, int key)
  79. {
  80.     Node* q = NULL;
  81.  
  82.     while(p)
  83.     {
  84.         if(p->data == key)
  85.         {
  86.             q->next = p->next;
  87.             p->next = first;
  88.             first = p;
  89.         }
  90.         else
  91.         {
  92.             q = p;
  93.             p = p->next;
  94.         }
  95.     }
  96. }
  97. */
  98.  
  99.  
  100.  
  101. int main()
  102. {
  103.     struct Node* temp;
  104.     int A[] = { 3, 5, 7, 10, 25, 8, 32, 2 };
  105.     create(A, 8);
  106.     Display(first);
  107.  
  108.     LinkedListDisplayReverse(first);
  109.     printf("\n");
  110.     LinkedListCount(first);
  111.     LinkedListSum(first);
  112.     printf("\n ");
  113.     Display(first);
  114.     return 0;
  115. }
  116.  
Advertisement
Add Comment
Please, Sign In to add comment