找出链表的中点

python实现:

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
class Node:
def __init__(self, data, next):
self.data = data
self.next = next

def find_mid_of_list(head):
quick, slow = head, head
i, j = 1, 2

while quick is not None:
while j:
quick = quick.next
if quick is None:
break j -= 1

if j == 2:
return [slow]
elif j == 1:
return [slow, slow.next]

while i:
slow = slow.next
if slow is None:
break i -= 1
i, j = 1, 2

return None

if __name__ == "__main__":
import sys
import os
if len(sys.argv) < 2:
print("useage:%s <num_list>" % sys.argv[0])
os._exit(-1)

t = sys.argv[1]
head = None
for c in t:
node = Node(c, None)
node.next = head
head = node

for x in find_mid_of_list(head):
print(x.data)