题解 | #链表的奇偶重排#
链表的奇偶重排
http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
odd 连接奇数节点
even 连接偶数节点
最终让odd尾指向even头就好了
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head || head->next == nullptr) return head; ListNode* odd = nullptr, *oddEnd = nullptr; ListNode* even = nullptr, *evenEnd = nullptr; while(head){ ListNode* cur = head; head = head->next; if(!odd) odd = oddEnd = cur; else{ oddEnd->next = cur; oddEnd = cur; } if(head){ cur = head; head = head->next; if(!even) even = evenEnd = cur; else{ evenEnd->next = cur; evenEnd = cur; evenEnd->next = nullptr; } } } oddEnd->next = even; return odd; } };
优化简化代码
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head || head->next == nullptr) return head; ListNode* odd = nullptr, *oddEnd = nullptr; ListNode* even = nullptr, *evenEnd = nullptr; while(head){ !odd?oddEnd = odd = head : oddEnd = oddEnd->next=head; head = head->next; if(head){ ListNode* cur = head; head = head->next; !even?even = evenEnd = cur:evenEnd = evenEnd->next = cur; evenEnd->next = nullptr; } } oddEnd->next = even; return odd; } };