解题思路:
- 设置两个列表,分别保存链表中的奇数结点和偶数结点
- 直接根据链表中的值创建新节点,直到完成实现链表的奇偶重排
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def oddEvenList(self , head: ListNode) -> ListNode:
# write code here
if not head:
return head
res = ListNode(-1)
lst1 = []
lst2 = []
p = head
count = 1
while p:
if count % 2 != 0:
lst1.append(p.val)
else:
lst2.append(p.val)
count += 1
p = p.next
print(lst1, lst2)
q = res
for i in range(len(lst1)):
q.next = ListNode(lst1[i])
q = q.next
for i in range(len(lst2)):
q.next = ListNode(lst2[i])
q = q.next
return res.next