xCircle

Circular linked list

Jan 16th, 2023 (edited)
970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Node structure
  6. struct Node {
  7.     int data;
  8.     Node* next;
  9. };
  10.  
  11. // Function to insert a node at the end of the list
  12. void push(Node** head_ref, int data) {
  13.     Node* new_node = new Node();
  14.     new_node->data = data;
  15.     new_node->next = *head_ref;
  16.     Node* temp = *head_ref;
  17.  
  18.     if (*head_ref != NULL) {
  19.         while (temp->next != *head_ref)
  20.             temp = temp->next;
  21.         temp->next = new_node;
  22.     }
  23.     else
  24.         new_node->next = new_node;
  25.  
  26.     *head_ref = new_node;
  27. }
  28.  
  29. // Function to print the list
  30. void printList(Node* head) {
  31.     Node* temp = head;
  32.     if (head != NULL) {
  33.         do {
  34.             cout << temp->data << " ";
  35.             temp = temp->next;
  36.         } while (temp != head);
  37.     }
  38. }
  39.  
  40. int main() {
  41.     Node* head = NULL;
  42.     push(&head, 1);
  43.     push(&head, 2);
  44.     push(&head, 3);
  45.     push(&head, 4);
  46.  
  47.     cout << "Circular Linked List: ";
  48.     printList(head);
  49.  
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment