# LeetCode Reorder List

Problem Description

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

Problem Solution

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
list<int> intList;
public:

return;
int listSize=0;
while(p)
{
intList.push_back(p->val);
p=p->next;
listSize++;
}
list<int> tmpList; //setup a new list to store the target value
list<int>::iterator iterBegin=intList.begin();
for(int i=0;i<listSize/2;++i) //traverse the first half of list
{
tmpList.push_back(*iterBegin++); //first push the begin value of list
tmpList.push_back(intList.back()); //second push the last value of list
intList.pop_back(); //third, pop the last value of list
}
if(listSize%2) //if the list size is odd, last value of list need to be pushed
tmpList.push_back(intList.back());
list<int>::iterator tIter=tmpList.begin();
while(p && tIter != tmpList.end())  //traverse the list and change its value
{
p->val=*tIter++;
p=p->next;
}
}
};

posted @ 2014-04-17 18:27  ballwql  阅读(124)  评论(0编辑  收藏