- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRemoveLoopLL.py
More file actions
Latest commit
99 lines (88 loc) · 1.97 KB
/
Copy pathRemoveLoopLL.py
File metadata and controls
99 lines (88 loc) · 1.97 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
'''
remove the loop in linked list
'''
classNode(object):
def__init__(self,data=None,next=None):
self.data=data
self.next=next
'''
given the head node of the linked list,
find how big is the loop
return the length of the loop and a node in the loop
'''
defloop_len(head):
'''
create tow pointers with different speed,
save the node they meet to calculate the length of the loop
'''
# fast = Node()
# slow = Node()
# fast.next = head
# slow.next = head
fast=head
slow=head
whilefastandslow:
fast=fast.next.next
slow=slow.next
iffast==slow:
start_loop=fast
break
# the length of the loop
# self pointing node, loop length is zero
p=start_loop
length=0
whilep:
p=p.next
length+=1
ifp==start_loop:
break
return (length,start_loop)
defremove_loop(head):
'''
create two pointer wit the distance of the loop's length
when the two pointers meet again,that's the start of the loops
remove the link between the previous node and the start node of the loop
'''
loop_length,start_loop=loop_len(head)
# p1, the start node, p2 the nex
# p1 = Node()
# p2 = Node()
# p3 = Node()
p1=head
# p2 = p1.next
p3=head
k=loop_length
whilek:
p3=p3.next
k-=1
# move the two pointers to the start loop node
# while p1 != start_loop:
# p1 = p1.next
# p2 = p2.next
# p3 = p3.next
whilep1.next!=p3.next:
p1=p1.next
# p2 = p2.next
p3=p3.next
# remove the link between p1 and p3
p3.next=None
N=6
nodes= [Node(data=d) fordinrange(N)]
foriinrange(N-1):
nodes[i].next=nodes[i+1]
nodes[N-1].next=nodes[2]
head=nodes[0]
defPrintNodes(head):
data= []
seen_nodes=set()
node=head
whilenode:
data.append(str(node.data))
ifnodeinseen_nodes:
break
seen_nodes.add(node)
node=node.next
print"->".join(data)
PrintNodes(head)
remove_loop(head)
PrintNodes(head)