forked from codescoop/Play-with-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17_circular_linked_list_insertion.cpp
104 lines (79 loc) · 2.04 KB
/
17_circular_linked_list_insertion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
TOPIC: Circular Linked List - Insertion
It is a Linked list in which last node points to the head of linked list.
Eg:
___ ___ ___ ___ ___
head---> |1|_| --> |2|_| --> |3|_| --> |4|_| --> |5|_| --
^ |
'----------------------------------------------'
Some real life application of circular linked list:-
- CPU algorithms
- Used to implement Queue data structure
*/
#include <iostream>
using namespace std;
// Linked List
class Node{
public:
int data;
Node *next;
// constructor
Node(int d)
{
data = d;
next = NULL;
}
};
// Insertion in Circular linked list
void insertAtHead(Node *&head, int d)
{
// step 1 (creating a new node)
Node *n = new Node(d);
n->next = head;
// step 2 (creating a loop)
if(head == NULL)
{
n->next = n; // creating a self loop
}
else
{
// traverse towards the end of linked list
Node *temp = head;
while(temp->next != head)
{
temp = temp->next;
}
temp->next = n; // creating a self loop
}
// step 3 (making head points towards new node)
head = n;
return;
}
// Display circular linked list
void print(Node *head)
{
Node *temp = head;
while(temp->next != head) // printing values till 2nd last node
{
cout << temp->data << " -> ";
temp = temp->next;
}
cout << temp->data; // to print the last node value
cout << endl;
}
// function to drive code
int main()
{
Node *head = NULL;
insertAtHead(head, 40);
insertAtHead(head, 30);
insertAtHead(head, 20);
insertAtHead(head, 10);
cout << "Circular Linked List [Insert at head]: ";
print(head);
return 0;
}
/*
OUTPUT:
Circular Linked List [Insert at head]: 10 -> 20 -> 30 -> 40
*/