-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersections_of_two_LiunkedList.cpp
133 lines (111 loc) · 3.05 KB
/
Intersections_of_two_LiunkedList.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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
};
class Solution {
private:
Node* detectLoop(Node* head) {
Node* slow = head;
Node* fast = head;
// Use the two-pointer technique to detect a loop
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
// If pointers meet, a loop is detected
if(slow == fast) {
// Move one pointer to head and find the start of the loop
slow = head;
while(slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow; // Starting point of the loop
}
}
return nullptr; // No loop detected
}
public:
// Function to remove a loop in the linked list
void removeLoop(Node* head) {
// Detect the starting point of the loop
Node* loopStart = detectLoop(head);
if(loopStart == nullptr) return; // No loop to remove
// Find the last node in the loop
Node* mover = loopStart;
while(mover->next != loopStart) {
mover = mover->next;
}
// Break the loop
mover->next = nullptr;
}
};
// class Solution {
// private:
// public:
// ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// if(headA == nullptr || headB == nullptr){
// return nullptr;
// }
// int len1 = 0;
// int len2 = 0;
// ListNode* tempA = headA;
// ListNode* tempB = headB;
// while(tempA){
// len1++;
// tempA = tempA->next;
// }
// while(tempB){
// len2++;
// tempB = tempB->next;
// }
// if(len1 > len2){
// int diff = len1 - len2;
// while(diff--){
// headA = headA->next;
// }
// }else{
// int diff = len2 - len1;
// while(diff--){
// headB = headB->next;
// }
// }
// while(headA){
// if(headA == headB){
// return headA;
// }
// headA = headA->next;
// headB = headB->next;
// }
// return nullptr;
// }
// };
// Function to create a new node
Node* newNode(int key) {
Node* temp = new Node();
temp->data = key;
temp->next = nullptr;
return temp;
}
// Function to print the linked list
void printList(Node* head) {
Node* temp = head;
while(temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main(){
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = head->next;
Solution ob;
ob.removeLoop(head);
printList(head);
return 0;
}