-
Notifications
You must be signed in to change notification settings - Fork 0
/
DelAndRevCirLL.cpp
62 lines (55 loc) · 1.37 KB
/
DelAndRevCirLL.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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* reverse(Node* head) {
// cout << "How many time is this called? " << endl;
if(!head) return head;
if(head->next == head)
return head;
Node* ptr = head, *nextPtr = head->next, *prevPtr = head;
while(prevPtr->next != head)
prevPtr = prevPtr->next;
// cout << "LstNOdE: " << prevPtr->data << endl;
while(nextPtr != head) {
ptr->next = prevPtr;
prevPtr = ptr;
ptr = nextPtr;
if(ptr == head && nextPtr == head)
break;
nextPtr = nextPtr->next;
}
ptr->next = prevPtr;
return ptr;
}
// Function to delete a node from the circular linked list
Node* deleteNode(Node* head, int key) {
if(head->next == head){
if(key == head->data)
return NULL;
return head;
}
Node* prevPtr = head, *ptr = head->next;
if(key == head->data){
while(ptr->next != head)
ptr = ptr->next;
ptr->next = prevPtr->next;
head = prevPtr->next; // * Update new HEAD
prevPtr->next = NULL;
delete prevPtr;
} else {
while(ptr != head){
if(key == ptr->data){
prevPtr->next = ptr->next;
ptr->next = NULL;
delete ptr;
break;
}
prevPtr = ptr;
ptr = ptr->next;
}
}
return head;
}