题目描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
算法
(链表,模拟) O(n)
假设初始的链表是 L1→L2→L3→…→Ln。
分三步处理:
- 将链表拆分为前后两段,要求偶数长度时前后半段长度相等,奇数长度时,前半段比后半段长一个结点。
- 将后半段的指针都反向,变成:L1→L2→L3→…→L⌈n/2⌉←L⌈n/2⌉+1←…←Ln;
- 用两个指针分别从1和n开始往中间扫描,将后半段交替插入到前半段,变成:L1→n→L2→Ln−1→…;
时间复杂度分析:整个链表总共扫描三次,第一次求总长度,第二次将后半段反向,第三次将后半段交替插入前半段,所以总时间复杂度是 O(n)。
C++代码:
/**
* 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) return ;
if(!head->next) return;
//拆分
int n=0;//局部变量一定要初始化
for(ListNode* p = head;p;p=p->next) n++;
cout<<n<<endl;
ListNode* mid = head;
for(int i =0;i<(n+1)/2-1;i++) mid = mid->next; //条件
ListNode *sec = mid->next;
mid->next = 0;//前半串串尾置空
//逆序
ListNode* cur = sec->next;
sec->next = 0;//后半串的头结点在逆序后变成尾结点,其next为空,之后sec作为cur的前驱
while(cur)//退出条件为cur为空,此时cur的原前驱为后半串的头结点
{
ListNode* tmp = cur->next;
cur->next = sec;
sec = cur;
cur = tmp;
}
//合并
//奇数长度,前半段比后半段多以;偶数长度,前后一样长
//直接用head遍历前半段,head是形参
while(sec){
//ListNdoe* next1 = head->next1; 此句多余
ListNode* next2 = sec->next;
sec->next = head->next;
head->next = sec;
sec=next2;
head=head->next->next;
}
}
};