Odd Even Linked List
Problem: Odd Even Linked List
We can use two pointer to store odd linked list and even linked list separately. We can use another pointer to scan through the linked list and link current node to one of the two storing pointers in turn.
Code in Python:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return head
odd, even = ListNode(-1), ListNode(0)
h1, h2 = odd, even
switch = 1
while head:
if switch:
odd.next, head, switch = head, head.next, 0
odd = odd.next
else:
even.next, head, switch = head, head.next, 1
even = even.next
odd.next, even.next = h2.next, None
return h1.next