forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
C++Circular linked list implementation using singly linked list
87 lines (86 loc) · 1.67 KB
/
C++Circular linked list implementation using singly linked list
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int a)
{
data = a;
next = NULL;
}
};
Node *inserth(Node *head, int x, int pos)
{
Node *temp = new Node(x);
if (head == NULL)
{
temp->next = temp;
cout << "null" << endl;
return temp;
}
else if (pos == 1)
{
temp->next = head->next;
head->next = temp;
int t = head->data;
head->data = temp->data;
temp->data = t;
return head;
}
Node *curr = head;
for (int i = 0; i < pos - 2; i++)
curr = curr->next;
temp->next = curr->next;
curr->next = temp;
return head;
}
Node *del(Node *head, int pos)
{
Node *curr = head;
if (pos == 1)
{
head->data = head->next->data;
Node *ptr = head->next;
head->next = head->next->next;
delete(ptr);
return head;
}
for (int i = 0; i < pos - 2; i++)
curr = curr->next;
Node *next = curr->next;
curr->next = curr->next->next;
delete (next);
return head;
}
void print(Node *head)
{
Node *curr = head;
do
{
cout << curr->data << " ";
curr = curr->next;
} while (curr != head);
}
int main()
{
Node *head = NULL;
head = inserth(head, 10, 1);
print(head);
cout << endl;
head = inserth(head, 20, 1);
print(head);
cout << endl;
head = inserth(head, 30, 1);
print(head);
cout << endl;
head = inserth(head, 50, 3);
print(head);
cout << endl;
head = inserth(head, 100, 4);
print(head);
cout << endl;
head = del(head, 5);
print(head);
cout << endl;
}