leetcode之Reorder List

问题描述如下:

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

问题链接

cpp代码如下:

class Solution {
public:
    void reorderList(ListNode *head) {
        if(head==NULL||head->next==NULL||head->next->next==NULL)return;
        ListNode* f=head,*s=head;
        while(true){
            f=f->next;
            if(!f)break;
            f=f->next;
            if(!f)break;
            s=s->next;
        }
        f=s->next;
        s->next=NULL;
        s=NULL;
        while(f->next){
            ListNode* tmp=f->next;
            f->next=s;
            s=f;
            f=tmp;
        }
        f->next=s;
        for(s=head;f!=NULL;){
            ListNode* tmp=f->next;
            f->next=s->next;
            s->next=f;
            s=f->next;
            f=tmp;
        }
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41773811
今日推荐