我写的代码
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head==NULL) return head; ListNode* evenHead = new ListNode(-1); ListNode* evenTail = evenHead; ListNode* p = head; while(p&&p->next){ ListNode* q = p->next; evenTail->next = q; evenTail = evenTail->next; p->next = q->next; q->next = NULL; if(p->next!=NULL) p = p->next; else break; } p->next = evenHead->next; return head; } };标准答案代码: 奇偶指针解耦移动,很漂亮。
class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head == NULL) return NULL; ListNode* odd = head, *even = head->next, *evenHead = even; while (even != NULL && even->next != NULL) { odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } odd->next = evenHead; return head; } };