Created
September 1, 2014 15:12
-
-
Save bluven/33b256e389cd4156a417 to your computer and use it in GitHub Desktop.
find middle node in singly linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
class Node(object): | |
def __init__(self, value, next=None): | |
self.value = value | |
self.next = next | |
def find_middle(node): | |
slow = fast = node | |
while fast: | |
fast = fast.next | |
if fast: | |
fast = fast.next | |
slow = slow.next | |
return slow | |
def gen_link(num): | |
node = None | |
for i in range(num): | |
node = Node(i, node) | |
return node | |
n = gen_link(11) | |
m = find_middle(n) | |
print n.value, m.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment