problem:
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}
这道题最开始的思路是采用4个指针,p1,p2,p3,p4,p1指向头节点,p4指向尾节点,p2=p1->next,p3指向尾节点的前一个节点,然后将p4插入p1与p2之间,
从而p3成为尾节点,再将p1=p2,p4=p3,重复以上步骤。
该算法的代码提交后,提示超时,于是想了另一种算法,即开辟一个数组,数组元素的个数与链表节点个数一致,数组元素类型为ListNode *,遍历链表,
将链表中节点的地址放入数组中,存放位置为该节点根据题目要求最后应该存在的位置。
最后扫节点连接成描一遍组数,将数组中存放的一个单链表,从而得出最后解。
该算法的代码提交后,结果为Accepted.
代码如下:
class Solution {
public:
void reorderList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(NULL == head) return;
ListNode *p = head;
//计算链表节点个数
int num = 0;
while(p){
num++;
p=p->next;
}
vector<ListNode *> vec(num);
int i = 0;
p = head;
//将前num/2的节点放入数组中
while(p&&i<=num-1){
vec[i] = p;
p=p->next;
i+=2;
}
if(i==num) i--;
else if(i==num+1) i-=3;
//将后num/2个节点放入链表中
while(p)
{
vec[i] = p;
p=p->next;
i-=2;
}
//最后将数组中的节点连接起来
for(int k=0; k<num-1;k++){
vec[k]->next = vec[k+1];
}
vec[num-1]->next = NULL;
}
};
.