思路:分别处理奇偶,保存奇偶的第一个和最后一个节点,注意最后链接的时候需要把偶数的next去掉再拼接不然就成环了
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next or not head.next.next:
return head
first_odd = head
first_even = head.next
last_odd = head
last_even = head.next
current_node = first_even.next
node_num = 3
while current_node:
next_node = current_node.next
if node_num % 2 == 1:
last_odd.next = current_node
last_odd=current_node
else:
last_even.next = current_node
last_even=current_node
current_node = next_node
node_num += 1
last_odd.next=first_even
last_even.next=None
return first_odd