-
Notifications
You must be signed in to change notification settings - Fork 0
/
Costum_library3-circular list added.cpp
121 lines (116 loc) · 2.62 KB
/
Costum_library3-circular list added.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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
Node(int x){
data = x;
next = NULL;
}
};
int countNodes(Node *head){
if(head==NULL){
return 0;
}
int count = 1;
Node *curr = head->next;
while(curr!=head){
count++;
curr = curr->next;
}
return count;
}
void printList(Node *head){
Node *curr = head->next;
cout << head->data << " ";
while(curr!=head){
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
Node* insertAtHead(Node *head,int x){
Node *temp = new Node(x);
if(head==NULL){
temp->next = temp;
return temp;
}
// Node *curr = head;
// while(curr->next!=head){
// curr = curr->next;
// }
// temp->next = head;
// curr->next = temp;
// return temp;
temp->next = head->next;
head->next = temp;
swap(head->data, temp->data);
return head;
}
Node *insertAtLast(Node *head, int x){
Node *temp = new Node(x);
if(head==NULL){
temp->next = temp;
return temp;
}
// Node *curr = head;
// while(curr->next!=head){
// curr = curr->next;
// }
// temp->next = curr->next;
// curr->next = temp;
// return head; it is O(N) solution
temp->next = head->next;
head->next = temp; //Tricky O(1) solution
swap(head->data, temp->data);
return temp;
}
Node* deleteHead(Node *head){
Node *temp = head->next;
head->data = head->next->data;
head->next = head->next->next;
delete temp;
return head;
}
Node* deleteLast(Node *head){
Node *curr = head->next;
while(curr->next->next!=head){
curr = curr->next;
}
Node *temp = curr->next;
curr->next = head;
delete temp;
return head;
}
Node *deleteKthNode(Node* head,int pos){
if(pos==1){
head = deleteHead(head);
return head;
}
pos = pos - 2;
Node *curr = head;
while(pos!=0 &&curr->next!=head){
curr = curr->next;
pos--;
}
if(curr->next==head){
head = deleteLast(head);
return head;
}
Node *temp = curr->next;
curr->next = curr->next->next;
delete temp;
return head;
}
int main(){
Node *head = NULL;
head = insertAtLast(head, 4);
head = insertAtLast(head, 15);
head = insertAtLast(head, 7);
head = insertAtLast(head, 40);
printList(head);
head = deleteKthNode(head, 4);
printList(head);
cout << countNodes(head);
return 0;
}