leetcode 328 Odd Even Linked List

题目链接:https://leetcode.com/problems/odd-even-linked-list/

思路分析:题目为链表操作题,比较容易。需要特别注意的是对于特殊情况的处理,如当链表为空或者链表的长度为1时,不存在第偶数个结点组成的链表。

 

代码如下:

# 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 or not head.next: return head
        odd_visit, even_visit = head, head.next
        head_odd, head_even = head, head.next
        visit, node_count = head.next.next, 0
        while visit:
            node_count += 1
            if node_count & 1:
                odd_visit.next = visit
                odd_visit = visit
            else:
                even_visit.next = visit
                even_visit = visit
            visit = visit.next
        odd_visit.next = even_visit.next = None
        odd_visit.next = head_even
        return head_odd

 

你可能感兴趣的:(leetcode 328 Odd Even Linked List)