没看答案
不理解的可以画图,按步骤用图解去理解。
但该方法在OJ上效果很差。
class Solution:
def oddEvenList(self, head):
len = curr = head
length = 0
# 遍历一遍链表,记录链表长度
while len:
len = len.next
length += 1
for i in range(length//2):
temp = curr
while temp.next.next:
node1 = temp.next
node2 = node1.next
temp.next = node2
node1.next = node2.next
node2.next = node1
temp = node2
curr = curr.next
return head
思路
双指针:
- 声明两个指针,分别用来指向奇数位置和偶数位置的节点;
- 画图,把步骤用图解表示出来,很容易就理解了。
Python
class Solution:
def oddEvenList(self, head):
if head and head.next:
odd = head
curr = even = head.next
while odd and even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = curr
return head
else:
return head
双端队列:把奇数和偶数位置节点存储在不同的双端队列,然后再重新组成一个链表。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
from collections import deque
class Solution:
def oddEvenList(self , head ):
# write code here
if not head:
return head
queue1 = deque()
queue2 = deque()
pre = curr = ListNode(100)
counter = 1
while head:
if counter % 2 == 1:
node = head
head = head.next
node.next = None
queue1.append(node)
counter += 1
else:
node = head
head = head.next
node.next = None
queue2.append(node)
counter += 1
while queue1:
tmp = queue1.popleft()
curr.next = tmp
curr = curr.next
while queue2:
tmp = queue2.popleft()
curr.next = tmp
curr = curr.next
return pre.next
C++
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* slow = head;
ListNode* fast = head->next;
ListNode* stay = fast;
while (fast != nullptr && fast->next != nullptr) {
slow->next = fast->next;
slow = slow->next;
fast->next = slow->next;
fast = fast->next;
}
slow->next = stay;
return head;
}
};
复杂度分析:
- 时间复杂度:O(n),其中 n 是链表的节点数。需要遍历链表中的每个节点,并更新指针。
- 空间复杂度:O(1)。只需要维护有限的指针。