Created
December 26, 2018 02:31
-
-
Save kanrourou/be7e26c01a15ae970d1aab560a91bc9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 || !head->next)return; | |
ListNode* fast = head, *slow = head; | |
//partition | |
while(fast->next && fast->next->next) | |
{ | |
fast = fast->next->next; | |
slow = slow->next; | |
} | |
auto head2 = slow->next; | |
slow->next = nullptr; | |
//reverse second | |
head2 = reverse(head2); | |
//merge second list into first list | |
auto curr1 = head, curr2 = head2; | |
while(curr2) | |
{ | |
auto tmp = curr2->next; | |
curr2->next = curr1->next; | |
curr1->next = curr2; | |
curr1 = curr1->next->next; | |
curr2 = tmp; | |
} | |
} | |
private: | |
ListNode* reverse(ListNode* head) | |
{ | |
ListNode* prev = head, *curr = head->next; | |
prev->next = nullptr; | |
while(curr) | |
{ | |
auto tmp = curr->next; | |
curr->next = prev; | |
prev = curr; | |
curr = tmp; | |
} | |
return prev; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment