【算法训练】LeetCode#328 奇偶链表
一、描述
328. 奇偶链表
给定单链表的头节点 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]
二、思路
这道题就是链表的遍历操作,没什么其他解法吧(应该)。
三、解题
public static class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null || head.next.next == null){
return head;
}
ListNode middle = head; // 作为划分点
while (middle.next != null){
middle = middle.next;
}
ListNode tail = middle; // tail到尾节点
ListNode cur = head.next;
ListNode pre = head;
while (cur != middle){
// 偶数节点放到尾节点后
pre.next = cur.next;
cur.next = null;
tail.next = cur; // 移动尾节点
tail = tail.next;
cur = pre.next;
if (cur == middle){
return head;
}
cur = cur.next;
pre = pre.next;
}
pre.next = cur.next;
cur.next = null;
tail.next = cur; // 移动尾节点
return head;
}
}

浙公网安备 33010602011771号