-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLAB3_Q2.cpp
176 lines (141 loc) · 3.16 KB
/
LAB3_Q2.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#include <iostream>
using namespace std;
class Node
{
public:
//data
int data;
//pointer to the next node
Node * next;
// constructor that makes the pointer to NULL
Node()
{
next = NULL;
}
};
class linkedList
{
;
public:
// head => node type pointer
Node * head;
Node * tail;
//constructor
linkedList()
{
head=NULL;
tail=NULL;
}
// circles inside each other
//rules to link circle
//insert
void insert(int value)
{
Node * temp = new Node;
//Insert value in node
temp->data = value;
//1st node only
if(head==NULL){
head = temp;
}
//any other node
else{
tail->next= temp;
}
tail = temp;
tail->next = head;
}
void insertAt(int pos, int value){
//reach the lace before pos
Node * current = head;
int i=1;
int c= Count();
if(pos <= c){
while (i<pos-1){
i++;
current = current->next;
}
//create a node
Node *temp = new Node;
temp -> data = value;
//move pointers like magic
temp->next = current->next;
current->next = temp;
}
else{
cout<<"Linked List does not have that many elements." <<endl;
}
//update the code for 1st position
}
//deletion
void delet(){
//store the tail in temp
Node * temp = tail;
// before tail has to point to NULL
Node * current = head;
while(current->next != tail){
current = current->next;
}
current->next = head;
//update tail
tail = current;
//delete temp
delete temp;
}
//deletion at position
void deletAt(int pos)
{
Node * current=new Node;
Node * previous=new Node;
current=head;
for(int i=1;i<pos;i++)
{
previous=current;
current=current->next;
}
previous->next=current->next;
}
int Count()
{
int i = 0; // Initialize count
class Node* current = head; // Initialize current
while (current->next != head)
{
i++;
current = current->next;
}
return i+1;
}
//display
void display(){
Node * current = head;
cout<<current->data<<"->";
current=current->next;
while(current != head){
cout<< current->data<<"->";
current = current->next;
}
cout<<endl;
}
};
int main()
{
linkedList l1;
l1.insert(1);
l1.insert(2);
l1.insert(3);
l1.insert(4);
l1.insert(5);
l1.insert(6);
l1.display();
cout<<"No. of elements is: ";
cout<<l1.Count()<<endl;
l1.delet();
l1.deletAt(2);
l1.display();
l1.insertAt(10,4);
l1.display();
cout<<"No. of elements is: ";
cout<<l1.Count()<<endl;
return 0;
}