328. Odd Even Linked List

# 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
        """
        
        odd_dummy = ListNode(217)
        odd = odd_dummy
        even_dummy = ListNode(217)
        even = even_dummy
        
        cur = head
        count = 0
        while(cur):
            temp = cur.next
            count += 1
            if count % 2 == 1:
                cur.next = None
                odd.next = cur
                odd = odd.next
            else:
                cur.next = None
                even.next = cur
                even = even.next
            cur = temp
        odd.next = even_dummy.next
        return odd_dummy.next

Notes:

  1. Always check infinite loop: if we using a while(cur) loop to link cur to cur.next.next and put cur.next to tail (update tail with tail.next), the infinite loop is promised (if not utilize counting inside the loop).

  2. Always check Control Flow colon

  3. Always check conditional ==, don't just leave = there.

Last updated