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