328. 奇偶链表

时间:2020-05-16
本文章向大家介绍328. 奇偶链表,主要包括328. 奇偶链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。





方法一:

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        ji = head_ji = ListNode(-1)
        ou = head_ou = ListNode(-1)
        cur = head
        flag = 1
        while cur:
            # 奇数位节点
            if flag:
                ji.next = cur
                ji = ji.next
                flag = 0
            # 偶数位节点
            else:
                ou.next = cur
                ou = ou.next
                flag = 1
            cur = cur.next
        ou.next = None
        ji.next = head_ou.next
        return head_ji.next

方法二:

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        odd = head
        even_head = even = head.next
        while odd.next and even.next:
            odd.next = odd.next.next
            even.next = even.next.next
            odd = odd.next
            even = even.next
        odd.next = even_head
        return head

原文地址:https://www.cnblogs.com/panweiwei/p/12900145.html