Leetcode Problem143

Reorder List

问题描述:给定单链表L:L 0 → L 1 →…→ L n -1 → L n,将其重新排序为:L 0 → L n → L 1 → L n -1 → L 2 → L n -2 →…

问题解决:思路很简单,用一个栈将所有节点储存起来,并记录链表的长度n。然后将pop栈顶,放在L0后面,以此类推,总共做了n/2次(即前半部分与后半部分)。但是这样跑出来的结果TLE。看到了别人用了快慢指针的方法,之前也没用过,于是在网上查了一下,顾名思义就是一个指针跑得比较快另外一个比较慢。类比跑步,假设一个人一次跑两米,另一个一次跑一米,当前一个人跑到终点时另外一个人刚好跑了一半的距离。这种做法使得我们在不用遍历整个链表的情况下得以知道链表的中间节点。

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head||!head->next||!head->next->next) return;
        ListNode *fast=head,*slow=head;
        while(fast->next&&fast->next->next)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        //找到中间节点
        ListNode *mid=slow->next,*tmp;
        slow->next=NULL;
        ListNode *pre=NULL,*last=mid;
        //将后半部分的链表倒转
        while(last)
        {
            tmp=last->next;
            last->next=pre;
            pre=last;
            last=tmp;
        }
        ListNode *p=head;
        while(p&&pre)
        {
            tmp=p->next;
            p->next=pre;
            pre=pre->next;
            p->next->next=tmp;
            p=tmp;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/vandance/article/details/82382053