-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlistdetectloop.cs
91 lines (70 loc) · 1.68 KB
/
linkedlistdetectloop.cs
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
using System;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
}
}
public class Node
{
public int Data {get; set;}
public Node Next {get; set;}
public Node(int newdata)
{
Data = newdata;
Next = null;
}
}
public class LinkedList
{
public Node Root {get; set;}
public LinkedList()
{
Root = null;
}
public void DetectAndRemoveLoop(Node node)
{
Node slow_p = node;
Node fast_p = node;
if(node == null || node.Next == null)
return;
slow_p = node.Next;
fast_p = node.Next.Next;
while(fast_p != null && fast_p.Next != null)
{
if(slow_p == fast_p)
{
break;
}
slow_p = slow_p.Next;
fast_p = fast_p.Next.Next;
}
if(slow_p == fast_p)
{
slow_p = node;
while(slow_p.Next != fast_p.Next)
{
slow_p = slow_p.Next;
fast_p = fast_p.Next;
}
fast_p.Next = null;
}
}
public bool DetectLoop(Node node)
{
Node slow_p = node;
Node fast_p = node;
while(slow_p != null && fast_p != null && fast_p.Next != null)
{
slow_p = slow_p.Next;
fast_p = fast_p.Next.Next;
if(slow_p == fast_p)
{
return true;
}
}
return false;
}
}