1、先确定节点个数,再按照要求调整节点顺序
ListNode* oddEvenList(ListNode* head) {
ListNode* last = head;
ListNode* cur = head;
int nums = 1;
ListNode* odds = head;
int total = 0;
while (cur) {
total++;
cur = cur->next;
}
cur = head;
while (total) {
if (nums % 2 == 1 && nums != 1) {//odd
last->next = cur->next;
ListNode* oddsnext = odds->next;
odds->next = cur;
cur->next = oddsnext;
odds = cur;
cur = last->next;
}
else {
last = cur;
cur = cur->next;
}
nums++;
total--;
}
return head;
}
2、分离奇偶节点,然后合并
ListNode* oddEvenList(ListNode* head) {
if (head == NULL || head->next == NULL || head->next->next == NULL)//长度小于等于2不用调
return head;
ListNode* odd = head, * even = head->next, * evenf = head->next;
ListNode* cur = head->next->next;
while (cur) {
odd->next = cur;
odd = cur;
cur = cur->next;
if (cur) {
even->next = cur;
even = cur;
cur = cur->next;
}
}
even->next = NULL;
odd->next = evenf;
return head;
}