# 奇偶鏈表問題

CSDN：奇偶鏈表問題

## 主要思路

``````// 奇數鏈表的開頭節點
ListNode oddStart = null;
// 奇數鏈表的結尾節點
ListNode oddEnd = null;
// 偶數鏈表的開頭節點
ListNode evenStart = null;
// 偶數鏈表的結尾節點
ListNode evenEnd = null;
// 當前遍歷到的節點
ListNode cur = head;
// 當前遍歷到的位置，根據題目意思，從 1 開始
int count = 1;
``````

``````oddStart = cur;
oddEnd = cur;
``````

``````oddEnd.next = cur;
oddEnd = cur;
``````

``````        if (evenEnd != null) {
evenEnd.next = null;
}

``````

``````oddEnd.next = evenStart;
``````

``````class Solution {
// 奇數節點和偶數節點放在一起
// 所有偶數下標的數一定要在奇數下標數之後（注意：是下標而非值）
public static ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return head;
}
ListNode oddStart = null;
ListNode oddEnd = null;
ListNode evenStart = null;
ListNode evenEnd = null;
ListNode cur = head;
int count = 1;
while (cur != null) {
if ((count & 1) == 1) {
// 奇數
if (oddStart == null) {
oddStart = cur;
} else {
oddEnd.next = cur;
}
oddEnd = cur;
} else {
// 偶數
if (evenStart == null) {
evenStart = cur;
} else {
evenEnd.next = cur;
}
evenEnd = cur;
}
count++;
cur = cur.next;
}
if (evenEnd != null) {
evenEnd.next = null;
}
oddEnd.next = evenStart;
return oddStart;
}
}
``````