Advertisement
193030

Cylcic Linked List

Nov 25th, 2021
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6.     int data;
  7.     struct Node* next;
  8. }*head = NULL;
  9.  
  10. void add(int arr[], int n, struct Node** head)
  11. {
  12.     struct Node* first;
  13.     first = new Node;
  14.     first->data = arr[0];
  15.     first->next = NULL;
  16.     struct Node* prev = first;
  17.     for (int i = 1; i < n; i++) {
  18.         struct Node* t = new Node;
  19.         t->data = arr[i];
  20.         t->next = NULL;
  21.         prev->next = t;
  22.         prev = t;
  23.     }
  24.  
  25.     (*head) = first;
  26.     prev->next = first;
  27. }
  28.  
  29. void display(struct Node* p)
  30. {
  31.     struct Node* t = p;
  32.     do {
  33.         cout << p->data << endl;
  34.         p = p->next;
  35.     } while (p != t);
  36. }
  37.  
  38. int main()
  39. {
  40.     int arr[] = { 10, 20, 30 };
  41.     add(arr, sizeof(arr) / sizeof(arr[0]), &head);
  42.     display(head);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement