给定一个单链表 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.
思路:
根据上面的示例,我们可以看出,该链表重排,首先将链表从中间分成两条链表,其次,将后半部分链表逆置,最后再和前半部分链表一次交叉连接。
代码实现如下:
void reorderList(ListNode* head)
{
stack<ListNode*>s1;//后半部分链表逆置,我们选择用栈的后进先出的特点来实现
if(head==NULL||head->next==NULL)
return ;
ListNode* fast=head->next;//采用快慢指针来找到中间节点
ListNode* slow=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
fast=slow->next;
slow->next=NULL;
slow=head;
while(fast)
{
s1.push(fast);
fast=fast->next;
}
while(!s1.empty())
{
ListNode* top=s1.top();
ListNode* cur=slow->next;
slow->next=top;
top->next=cur;
s1.pop();
slow=cur;
}
return ;
}