DSA/linked-lists/c-or-cpp/circular.cpp

40 lines
768 B
C++
Raw Normal View History

#include <iostream>
using namespace std;
struct Node {
<EFBFBD> <EFBFBD>int data;
<EFBFBD> <EFBFBD>struct Node *next;
};
struct Node* head = NULL;
void insert(int newdata) {
<EFBFBD> <EFBFBD>struct Node *newnode = (struct Node *)malloc(sizeof(struct Node));
<EFBFBD> <EFBFBD>struct Node *ptr = head;
<EFBFBD> <EFBFBD>newnode->data = newdata;
<EFBFBD> <EFBFBD>newnode->next = head;
<EFBFBD> <EFBFBD>if (head!= NULL) {
<EFBFBD> <EFBFBD> <EFBFBD> while (ptr->next != head)
<EFBFBD> <EFBFBD> <EFBFBD> ptr = ptr->next;
<EFBFBD> <EFBFBD> <EFBFBD> ptr->next = newnode;
<EFBFBD> <EFBFBD>} else
<EFBFBD> <EFBFBD>newnode->next = newnode;
<EFBFBD> <EFBFBD>head = newnode;
}
void display() {
<EFBFBD> <EFBFBD>struct Node* ptr;
<EFBFBD> <EFBFBD>ptr = head;
<EFBFBD> <EFBFBD>do {
<EFBFBD> <EFBFBD> <EFBFBD> cout<<ptr->data <<" ";
<EFBFBD> <EFBFBD> <EFBFBD> ptr = ptr->next;
<EFBFBD> <EFBFBD>} while(ptr != head);
}
int main() {
<EFBFBD> <EFBFBD>insert(3);
<EFBFBD> <EFBFBD>insert(1);
<EFBFBD> <EFBFBD>insert(7);
<EFBFBD> insert(3);
<EFBFBD> <EFBFBD>insert(1);
<EFBFBD> <EFBFBD>insert(7);
<EFBFBD> <EFBFBD>cout<<"The circular linked list is: ";
<EFBFBD> <EFBFBD>display();
<EFBFBD> <EFBFBD>return 0;
}