-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter2.cs
More file actions
67 lines (56 loc) · 1.57 KB
/
Copy pathChapter2.cs
File metadata and controls
67 lines (56 loc) · 1.57 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
namespace CodingProblems
{
public class Chapter2
{
// with a delete twist instead of being just return
public static Node Problem2(Node node, int indexFromEnd)
{
var scout = node;
Node beforeToDelete = null;
for (int i = 1; i < indexFromEnd; i++)
{
if (scout == null)
{
return node;
}
scout = scout.Next;
}
while (scout.Next != null)
{
scout = scout.Next;
if (beforeToDelete == null)
{
beforeToDelete = node;
}
else
{
beforeToDelete = beforeToDelete.Next;
}
}
if (beforeToDelete == null)
{
return node.Next;
}
if (beforeToDelete.Next != null)
{
beforeToDelete.Next = beforeToDelete.Next.Next;
}
return node;
}
public static bool DetectLoops(Node node)
{
var slowIterator = node;
var fastIterator = node;
while (fastIterator != null && fastIterator.Next != null)
{
slowIterator = slowIterator.Next;
fastIterator = fastIterator.Next.Next;
if (slowIterator == fastIterator)
{
return true;
}
}
return false;
}
}
}