Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 26, 2018 02:31
Show Gist options
  • Save kanrourou/be7e26c01a15ae970d1aab560a91bc9d to your computer and use it in GitHub Desktop.
Save kanrourou/be7e26c01a15ae970d1aab560a91bc9d to your computer and use it in GitHub Desktop.
/**
* 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