具体思想:
直接指针操作,没啥可说的;
具体代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode* p = head;
ListNode* pre = head;
ListNode* q = head;
bool flag = false;
if (!head || !head->next)
return head;
q = head->next;
while (q != nullptr) {
if (flag) {
flag = false;
ListNode* temp = p->next;
pre->next = q->next;
p->next = q;
q->next = temp;
p = p->next;
q=pre->next;
}
else {
flag = true;
pre = pre->next;
q = q->next;
}
}
return head;
}
};