难度:中等
题目描述:
思路总结:思路很直接,odd和even两个指针遍历一遍,然后连接在一起,这题本质上和昨天做的题24.两两交换链表中的节点没啥区别。
题解一:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
#思路:两个指针遍历完连接。
if not head:return head
odd = head
even = head.next
pre = even
#如果更新后odd不空,even不空,但是even.next为None,说明后面已经没了。
while odd and even and even.next:#这里的边界条件是重点,正好满足了所有的情况。
nxt = even.next
odd.next = nxt
even.next = nxt.next
#update node
odd = odd.next
even = even.next
odd.next = pre
return head