Skip to content

Instantly share code, notes, and snippets.

@bluven
Created September 1, 2014 15:12
Show Gist options
  • Save bluven/33b256e389cd4156a417 to your computer and use it in GitHub Desktop.
Save bluven/33b256e389cd4156a417 to your computer and use it in GitHub Desktop.
find middle node in singly linked list
#!/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