给定一个单链表L:L0→L1→…→Ln-1→Ln,
重新排列后为: L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点的值的情况下进行原地操作。
例如,
给定链表 {1,2,3,4},按要求重排后为 {1,4,2,3}。
详见:https://leetcode.com/problems/reorder-list/description/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode* head) { if(head==nullptr||head->next==nullptr) { return; } ListNode* head1=head; ListNode* head2=head; while(head2&&head2->next) { head1=head1->next; head2=head2->next->next; } head2=head1->next; head1->next=nullptr; ListNode* pre=nullptr; ListNode* next=nullptr; while(head2) { next=head2->next; head2->next=pre; pre=head2; head2=next; } head2=pre; head1=head; ListNode* post1,*post2; while(head1&&head2) { post1=head1->next; post2=head2->next; head1->next=head2; head2->next=post1; head1=post1; head2=post2; } } };
参考:https://www.cnblogs.com/grandyang/p/4254860.html