328. 奇偶链表

https://leetcode-cn.com/problems/odd-even-linked-list/

解法一:

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        i, j = head, head.next  #奇链和偶链的工作指针
        head2 = head.next   #记录偶链头防丢失(奇链头为head)
        while j.next and j.next.next:   #奇链走两步,偶链也走两步
            i.next = i.next.next
            i = i.next
            j.next = j.next.next
            j = j.next
        if j.next:  #长度为奇,奇链多出一个
            i.next = i.next.next
            i = i.next
            j.next = None
        i.next = head2  #奇链接上偶链
        return head

最后更新于