解题思路:
将奇数位置构成一个新链表,偶数位置的节点也构成一个新链表,然后拼接起来即可。
具体代码如下:
# 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 or not head.next:
return head
singular = head
odd = head.next
tmp = odd.next
count = 1
ptr1 = singular
ptr1.next = None
ptr2 = odd
ptr2.next = None
while tmp:
if count % 2 == 1:
ptr1.next = tmp
tmp = tmp.next
ptr1 = ptr1.next
count += 1
else:
ptr2.next = tmp
tmp = tmp.next
ptr2 = ptr2.next
ptr2.next = None
count += 1
ptr1.next = odd
return singular