Repository navigation
Expand file tree
/
Copy path7_5_overlapping_loop_lists.cpp
More file actions
160 lines (154 loc) · 3.22 KB
/
Copy path7_5_overlapping_loop_lists.cpp
File metadata and controls
160 lines (154 loc) · 3.22 KB
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
#include <iostream>
using namespace std;
template <class T>
class LinkedList
{
struct node
{
T x;
node *next;
};
public:
LinkedList()
{
head = NULL;
curr = NULL;
}
node* getHead()
{
return head;
}
node* getCurrent()
{
return curr;
}
void addNode(struct node* b)
{
b->next = head;
head = b;
if(curr == NULL)
curr = head;
}
void addValue(T a)
{
node *n = new node;
n->x = a;
n->next = head;
head = n;
if(curr == NULL)
curr = head;
}
void rewind()
{
curr = head;
}
void next()
{
if( curr != NULL )
curr = curr->next;
}
int getValue()
{
if( curr != NULL )
return curr->x;
return 0;
}
int hasValue()
{
return ( curr != NULL ? true : false );
}
node* loopCheck()
{
node *a, *b;
int i=1,j=0;
a = head->next;
b = head->next;
b = b->next;
while(b!=NULL && b->next!=NULL && b!=head && b->next!=head && a!=b)
{
a = a->next;
b = b->next;
if(b->next == NULL)
break;
else
b = b->next;
}
if(b==NULL || b->next==NULL)
return NULL;
else if(b==head || b->next==head)
{
return head;
}
else
{
a = a->next;
while(a!=b)
{
a = a->next;
i++;
}
a = head;
b = head;
while(i>0)
{
b = b->next;
i--;
}
while(a!=b)
{
a = a->next;
b = b->next;
j++;
}
return a;
}
}
node* forkAndLoopCheck(struct node* b)
{
node *h1, *h2;
h1 = this->loopCheck();
head = b;
h2 = this->loopCheck();
if(h1 && h2)
{
node *temp;
temp = h1->next;
while(temp!=h2 && temp!=h1 && h1!=h2)
temp = h1->next;
if(h1==h2)
curr = h1;
else if(temp==h2)
curr = temp;
else
curr = NULL;
}
else
curr = NULL;
return curr;
}
private:
node *head;
node *curr;
};
int main()
{
LinkedList<int> L, M;
L.addValue(12);
L.addValue(10);
L.addValue(9);
M.addValue(8);
L.addNode(M.getHead());
L.addNode(L.getCurrent());
L.addValue(7);
L.addValue(5);
L.addValue(2);
M.addValue(6);
M.addValue(5);
M.addValue(3);
M.addValue(1);
if(L.forkAndLoopCheck(M.getHead()))
cout << "Value: " << L.getValue() << "\nPointer: " << L.getCurrent() << endl;
else
cout << "0" << endl;
return 0;
}