题意:
给你一个单链表 a1 a2 a3 a4 a5....an 让你变成 a1 an a2 an-1 a3 an-2 ....
这里牵涉到,单链表的倒置和两个单链表的合并。
class Solution {public: void reorderList(ListNode *head) { if (!head || !head->next)return; //空表和只有一个元素的链表不用操作 //快慢指针找中间位置 ListNode *fast = head; ListNode *slow = head; while (fast&&fast->next) { slow = slow->next; fast = fast->next->next; } //将后半段的链表倒置 ListNode *after = slow->next; slow->next = NULL; ListNode *pre = NULL; while (after){ ListNode *p = after->next; after->next = pre; pre = after; after = p; } //合并两个链表 ListNode *first = head; after = pre; while (first&&after){ ListNode *ftemp = first->next; ListNode *aftemp = after->next; first->next = after; first = ftemp; after->next = first; after = aftemp; } }};