Last active
January 26, 2016 02:42
-
-
Save addie/4a1f6c7425ee75117ad9 to your computer and use it in GitHub Desktop.
Splits a linked list of positive integers into two lists, one of even and one of odd integers. T:O(n) S:O(1)
This file contains 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
class Node: | |
def __init__(self, value=None, next=None): | |
self.value = value | |
self.next = next | |
def print_list(head): | |
while head: | |
print(head.value, end='->') | |
head = head.next | |
print() | |
def | |
def even_odd(head): | |
if not head: | |
return | |
odd = None | |
even = None | |
l1 = head | |
while l1: | |
if l1.value % 2 == 0: # even | |
if not even: | |
even = l1 | |
l2 = even | |
else: | |
l2.next = l1 | |
l2 = l2.next | |
else: # odd | |
if not odd: | |
odd = l1 | |
l3 = odd | |
else: | |
l3.next = l1 | |
l3 = l3.next | |
l1 = l1.next | |
if l2: l2.next = None | |
if l3: l3.next = None | |
return odd, even | |
head = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6)))))) | |
print_list(head) | |
odd, even = even_odd(head) | |
print_list(odd) | |
print_list(even) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment