题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}
.
用一个双向队列去存储其内容,再从首尾挂载到链表中。
代码:
/**
* 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)
{
deque<ListNode*>m_que;
ListNode* pNode = head;
if(pNode == NULL)
{
return;
}
pNode = pNode->next;
while(pNode)
{
m_que.push_back(pNode);
pNode = pNode->next;
}
pNode = head;
while(m_que.size() >= 2)
{
ListNode* backnode = m_que.back();
m_que.pop_back();
pNode->next = backnode;
pNode = backnode;
ListNode* frontnode = m_que.front();
m_que.pop_front();
pNode->next = frontnode;
pNode = frontnode;
pNode->next = NULL;
}
if(m_que.size()==1)
{
ListNode* tNode = m_que.back();
m_que.pop_back();
tNode->next = NULL;
pNode->next = tNode;
}
}
};