/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ classSolution { public: voidreorderList(ListNode* head){ if(head == NULL || head->next == NULL) return; ListNode *slow= head, *fast= head; while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode* middle = slow; ListNode* preCurrent = slow->next; while(preCurrent->next != NULL){ //use preCurrent->next to determine whether if there's more element need to reverse ListNode *tmp = preCurrent->next; preCurrent->next = tmp->next; tmp->next = middle->next; middle->next= tmp; } slow = head; //first part of the list fast = middle->next; //second part of the list while(slow != middle){ middle->next = fast->next; fast->next= slow->next; slow->next= fast; slow= fast->next; fast= middle->next; } } };
time complexity: $O(n)$ space complexity: $O(1)$
Solution 2
Another way is to use stack to keep all the second half nodes. Since stack is last in first out, we would get the last node when we rearrange the list.