拆分成奇数位链表跟偶数位链表,再拼接起来。交叉输出,注意一下边界。
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* oddEvenList(ListNode* head) { if(head == NULL){ return NULL; } // write code here ListNode *p = head; ListNode *odd = p->next; ListNode *q = odd; p->next = NULL; while(p != NULL && q != NULL){ p->next = q->next; q->next = NULL; if(p->next == NULL){ break; } p = p->next; q->next = p->next; q = q->next; p->next = NULL; } p->next = odd; return head; } };