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}
.
这个题如果不考虑空间复杂度,就简单多了,可以逆序复制保存一份,然后进行插入或合并,知道遇到相同的结点。很明显这不是题的本意。
这个题能想到的考察点有3个:
1)不同于数组或其他的容器类,不能直接获取总长度,所以不能直接获取到折半的分割点。想想判断一个链表是否存在环的问题,一种思路是令一个指针每次移动两步,一个移动一步,当二者再次相遇,我们就说环存在。就像长跑比赛的“套圈”。这里我们也设定两个指针,一个每次移动2步,一个移动1步,当两步的走到头的时候,一步的走了一半。
2)单向链表的就地逆置。
3)两个链表的合并,或者将链表A插入到链表B中。
//code
class Solution {
public:
void reorderList(ListNode *head) {
if(head == NULL || head->next == NULL)
return;
//find the half point
ListNode *pfast, *pslow;
pfast = pslow = head;
while (pfast->next)
{
pfast = pfast->next;
if(pfast->next)
pfast = pfast->next;
else
break;
pslow = pslow->next;
}
ListNode *head2 = pslow->next;
pslow->next = NULL;
//reverse head2
ListNode *p2 = head2;
ListNode *pre = NULL;
while(p2)
{
ListNode *p_next = p2->next;
p2->next = pre;
pre = p2;
p2 = p_next;
}
head2 = pre;
ListNode *p1 = head;
ListNode *q1,*p2,*q2;
p2 = head2;
//union the lists.
while (p2)
{
q1 = p1->next;
q2 = p2->next;
p1->next = p2;
p2->next = q1;
p2 = q2;
p1 = q1;
}
}
};