328. 奇偶链表
题意
奇数的链表结点插在偶数的链表结点前面;
解题思路
维护两条链表,分别记录下奇数和偶数的链表结点,最后将偶数链表的起始结点连接到奇数链表的末尾结点后面;
实现
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
odd, even = head, head.next
even_head = even
# 设置两条链表,分别记录奇数和偶数的链表结点
while even 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