class Solution {
public:
void reorderList(ListNode* head) {
if(!head || !head -> next || ! head -> next -> next) //长度小于2都不用处理
return;
ListNode *slow = head, *fast = head, *sec;
while(fast && fast -> next){ //快慢指针找到中间的节点
slow = slow -> next;
fast = fast -> next -> next;
}
fast = slow -> next; //fast标记为下一段
slow -> next = nullptr; //截断
reverseList(fast); //第二段反序
combineList(head, fast); //合并
}
void reverseList(ListNode*& head){
ListNode *left = head, *mid = head -> next, *right;
while(mid){
right = mid -> next; //right向右移动
left -> next = right; //left指向下一个点
mid -> next = head; //mid向左指
head = mid; //head记录头节点,也就是每一次中较右的节点
mid = right; //mid向右移动
}
}
void combineList(ListNode*& fir, ListNode*& sec){
while(sec){ //默认fir长1个单位 或 长度相等
ListNode *temp = sec;
sec = sec -> next;
//插入节点
temp -> next = fir -> next;
fir -> next = temp;
fir = temp -> next;
}
}
};
Accepted
12/12 cases passed (28 ms)
Your runtime beats 96.76 % of cpp submissions
Your memory usage beats 69.4 % of cpp submissions (17.3 MB)