文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Reorder List2. Solution
/**
* 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) {
return;
}
ListNode* p1 = head;
ListNode* p2 = head;
while(p2 && p2->next) {
p1 = p1->next;
p2 = p2->next->next;
}
ListNode* left = head;
ListNode* right = reverseList(p1->next);
p1->next = nullptr;
ListNode* new_head = new ListNode(0);
ListNode* current = new_head;
while(left && right) {
current->next = left;
left = left->next;
current = current->next;
current->next = right;
current = current->next;
right = right->next;
}
current->next = left?left:right;
head = new_head->next;
}
private:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* next = nullptr;
ListNode* current = head;
while(current) {
next = current->next;
current->next = pre;
pre = current;
current = next;
}
return pre;
}
};
网友评论