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}.
根据题目的要求将链表分成两部分,然后将后一半链表逆序之后插空加入到前一链表中。因此定义一个函数实现将后一部分链表进行逆序排列。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL) //处理异常情况
return head;
ListNode* tmphead = reverseList(head->next); //最终指向的是链表中的最后一个元素 head->next->next = head; head->next = NULL;
return tmphead;
}
void reorderList(ListNode *head) {
if(head==NULL || head->next==NULL)
return;
ListNode* pslow = head;
ListNode* pfast = head;
while(pfast&&pfast->next)
{
pfast = pfast->next->next;
pslow = pslow->next;
}
ListNode* head2 = pslow->next;
pslow->next = NULL; //将一个链表分成两部分
head2 = reverseList(head2);
if(head2==NULL)
return;
ListNode* p1 = head;
ListNode* p2 = head2;
ListNode* tmp = NULL;
while(p1!=NULL && p2!= NULL){
tmp = p1->next;
p1->next = p2;
p1 = tmp;
tmp = p2->next;
p2->next = p1;
p2 = tmp;
}
}
};
此处使用递归反转链表,运行时间是288ms,使用循环进行反转,代码运行时间为270ms。看来递归的时间效率还是差一点点。
本文介绍了一种链表重排序算法,该算法首先将链表分为前后两部分,然后将后半部分逆序并交错地合并到前半部分。文中提供了一个具体的C++实现示例,并比较了递归和循环两种逆序方法的性能。
640

被折叠的 条评论
为什么被折叠?



