Sakura

sakura

博客园 首页 新随笔 联系 订阅 管理

链表重排


#define Node ListNode
#define null NULL
class Solution {
public:
    void reorderList(ListNode *head) {
        if(head == null||head->next==null) return ;
        Node*first=head,*last=head, *pre=NULL;
        while(first && first->next) first=first->next->next, pre = last,last=last->next;
        Node* head2 = last;
        pre->next = NULL;
        head2 = reverse(head2);
        merge(head,head2);
//         return dummy.next;
        
        
    }
    Node* reverse(ListNode* h) {
        if(h==null || h->next==null) return h;
        Node *pre=null,*cur=h,*last=null;
        while(cur) {
            last = cur->next;
            cur->next = pre;
            pre = cur;
            cur = last;
        }
        return pre;
    }
    Node* merge(Node* l,Node* r) {
        Node dummy(0);
        Node* x = &dummy;
        int count=0;
        while(l &&r) {
            if(count%2==0) {
                //第一个
                x->next = l;
                l = l->next;//l1
                x = x->next;//l0
                x->next = NULL;
            }else{
                //第二个
                x->next = r;
                r = r->next;
                x = x->next;
                x->next = NULL;
                
            }
            
            
            ++count;
        }
        if(l) x->next = l;
        if(r) x->next = r;
        return dummy.next;
    }
};








posted on 2021-01-25 01:28  .geek  阅读(37)  评论(0编辑  收藏  举报