給定單鏈表,將奇數索引節點(1,3,5...)移至前面,偶數索引節點(2,4,6...)移至後面,保持組內相對順序。要求 O(1) 空間、O(n) 時間。
用兩個指針分別串聯奇數節點和偶數節點。遍歷鏈表,按索引奇偶將節點接到對應鏈表尾部。最後將奇數鏈表尾連接到偶數鏈表頭,偶數鏈表尾置空。
public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode oddTail = head;
ListNode evenHead = head.next;
ListNode evenTail = evenHead;
int idx = 1;
ListNode cur = head.next.next;
while (cur != null) {
if (++idx % 2 == 1) {
oddTail.next = cur;
oddTail = oddTail.next;
} else {
evenTail.next = cur;
evenTail = evenTail.next;
}
cur = cur.next;
}
evenTail.next = null;
oddTail.next = evenHead;
return head;
}
}