给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
有两种思路,一种通过快慢指针找到链表中间点,以中间点为分隔点拆分成两个链表,然后对后面的链表进行翻转,最后将这个两个链表组成一个新的链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *reverseList(ListNode *head)
{
ListNode *pRNext = NULL;
ListNode *pCur = head;
while(pCur)
{
ListNode *pCNext = pCur->next;
pCur->next = pRNext;
pRNext = pCur;
pCur = pCNext;
}
return pRNext;
}
public:
void reorderList(ListNode* head) {
if(NULL == head || NULL == head->next) return;
//通过快慢指针找到中间节点
ListNode *slow = head;
ListNode *fast = head;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode *pLeft = head;
ListNode *pTemp = slow->next;
slow->next = NULL;
ListNode *pRight = reverseList(pTemp);
while(pLeft && pRight)
{
ListNode *pLNext = pLeft->next;
ListNode *pRNext = pRight->next;
pLeft->next=pRight;
pRight->next = pLNext;
pLeft = pLNext;
pRight = pRNext;
}
}
};
另一种利用双端队列,前后依次pop
class Solution {
public:
void reorderList(ListNode* head) {
if(NULL == head || NULL == head->next) return;
ListNode *pCur = head;
deque<ListNode *> dq;
while(pCur)
{
dq.push_back(pCur);
pCur = pCur->next;
}
while(!dq.empty())
{
if(NULL == pCur)
{
pCur = dq.front();
}
else
{
pCur->next = dq.front();
pCur = pCur->next;
}
dq.pop_front();
if(dq.empty()) break;
pCur->next = dq.back();
dq.pop_back();
pCur = pCur->next;
}
if(pCur)
{
pCur->next = NULL;
}
}
};