Use a slow pointer and a faster pointer to reach the middle of the list. Push all the nodes into the stack while scanning. Then change the direction while popping the stack.
/**
* 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||!head->next->next)
return;
ListNode *slow,*fast;
stack<ListNode*> s;
slow=fast=head;
while(fast&&fast->next)
{
s.push(slow);
slow=slow->next;
fast=fast->next->next;
}
ListNode *temp=slow;
slow=slow->next;
temp->next=NULL;
if(!fast)//The list has even number of nodes
s.pop();
while(!s.empty())
{
temp=slow;
slow=slow->next;
temp->next=s.top()->next;
s.top()->next=temp;
s.pop();
}
}
};