LeetCode 题解工作台
奇偶链表
给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别分组,保持它们原有的相对顺序,然后把偶数索引节点分组连接到奇数索引节点分组之后,返回重新排序的链表。 第一个 节点的索引被认为是 奇数 , 第二个 节点的索引为 偶数 ,以此类推。 请注意,偶数组和奇数组内部的相对顺序应该与…
1
题型
5
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们可以用两个指针 和 分别表示奇数节点和偶数节点的尾节点。初始时,指针 指向链表的头节点 ,指针 指向链表的第二个节点 。另外,我们用一个指针 指向偶数节点的头节点 ,即指针 的初始位置。 遍历链表,我们将指针 指向 的下一个节点,即 $a.next = b.next$,然后将指针 向后移动一位,即 $a = a.next$;将指针 指向 的下一个节点,即 $b.next …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别分组,保持它们原有的相对顺序,然后把偶数索引节点分组连接到奇数索引节点分组之后,返回重新排序的链表。
第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。
请注意,偶数组和奇数组内部的相对顺序应该与输入时保持一致。
你必须在 O(1) 的额外空间复杂度和 O(n) 的时间复杂度下解决这个问题。
示例 1:

输入: head = [1,2,3,4,5] 输出: [1,3,5,2,4]
示例 2:

输入: head = [2,1,3,5,6,4,7] 输出: [2,3,6,7,1,5,4]
提示:
n ==链表中的节点数0 <= n <= 104-106 <= Node.val <= 106
解题思路
方法一:一次遍历
我们可以用两个指针 和 分别表示奇数节点和偶数节点的尾节点。初始时,指针 指向链表的头节点 ,指针 指向链表的第二个节点 。另外,我们用一个指针 指向偶数节点的头节点 ,即指针 的初始位置。
遍历链表,我们将指针 指向 的下一个节点,即 ,然后将指针 向后移动一位,即 ;将指针 指向 的下一个节点,即 ,然后将指针 向后移动一位,即 。继续遍历,直到 到达链表的末尾。
最后,我们将奇数节点的尾节点 指向偶数节点的头节点 ,即 ,然后返回链表的头节点 即可。
时间复杂度 ,其中 是链表的长度,需要遍历链表一次。空间复杂度 。只需要维护有限的指针。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return None
a = head
b = c = head.next
while b and b.next:
a.next = b.next
a = a.next
b.next = a.next
b = b.next
a.next = c
return head
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each node is visited exactly once. Space complexity is O(1) since no additional data structures are used beyond a few pointers, making this approach optimal for in-place reordering. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for in-place pointer manipulations without using extra arrays or lists.
- question_mark
Check whether relative ordering of odd and even nodes is preserved.
- question_mark
Watch for edge cases like empty lists, single-node lists, or lists with only even nodes.
常见陷阱
外企场景- error
Failing to reconnect the even sublist to the odd sublist at the end.
- error
Breaking the linked list by incorrectly updating next pointers, leading to cycles or null references.
- error
Assuming node values determine odd/even instead of node positions, which is a common misinterpretation.
进阶变体
外企场景- arrow_right_alt
Reordering nodes so that all nodes at prime indices appear before non-prime indices.
- arrow_right_alt
Segregating linked list nodes based on alternating property, such as positive and negative values, instead of odd and even positions.
- arrow_right_alt
Perform the reordering using a recursive approach instead of iterative pointer manipulation.