现在的位置: 首页 > 综合 > 正文

leetcode 第22-24题Merge k Sorted Lists & Swap Nodes in Pairs & Reverse Nodes in k-Group

2019年04月02日 ⁄ 综合 ⁄ 共 2267字 ⁄ 字号 评论关闭

Merge k Sorted Lists 该题可以在 Merge Two Sorted Lists的基础上进行,通过将k个链分成两两一组合并后,在不断递归这个过程即可

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode *p1=l1,*p2=l2;
        if(!1)return l2;
        else if(!l2)return l1;
        ListNode *ans=new ListNode(0);
        ListNode *lc=ans;
        while(p1&&p2)
        {
            if(p1->val<p2->val){lc->next=p1;p1=p1->next;lc=lc->next;}
            else {
                lc->next=p2;p2=p2->next;lc=lc->next;
            }
        }
        if(p2)while(p2){lc->next=p2;p2=p2->next;lc=lc->next;}
        else if(p1) while(p1){lc->next=p1;p1=p1->next;lc=lc->next;}
        lc =ans;
        ans=ans->next;
        delete lc;
        return ans;
    }
ListNode *mymerge(vector<ListNode *> &lists,int start,int end){
    if(start==end-1)return lists[start];
    if(start==end-2)return (mergeTwoLists(lists[start],lists[start+1]));
    return mergeTwoLists( mymerge(lists,start,(start+end)/2),mymerge(lists,(start+end)/2,end));
}
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode *ans=NULL;
        if(lists.size()==0)return ans;
        if(lists.size()==1)return lists[0];
        return mymerge(lists,0,lists.size());
        
        
    }
};

Swap Nodes in Pairs该题可以看成下一题的特例,只要对下一题的代码稍加修改,就可以解决该题,不过,因为该题逆序子链的长度始终是2,所以可以更简短明了的解决

class Solution {

public:
    ListNode *swapPairs(ListNode *head) {
        if(head==NULL)return head;
        ListNode *p=head,*q=head->next,*r;
        if(q==NULL)return head;
         p->next=q->next;
            q->next=p;
        head=q;
        while(p->next&&p->next->next){
            q=q->next;
            q=q->next->next;
            r=p;
            p=p->next;
            p->next=q->next;
            q->next=p;
            r->next=q;
            
        }
    return head;
        
    }

};

 Reverse Nodes in k-Group 该题思路可以考虑每次从原链表中取出长为k 的子串,通过头插法的方式逆序后,挂在结果链表后端,对于最后一个长不足k的子链,直接加在后面即可

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head==NULL||k<=1)return head;
        ListNode *p=head,*q=head,*r1=head,*r=head,*tmphead=NULL;
        int i=0;
       // while(p&&i<k){p=p->next;i++}
          // if(i<k)return head;
        tmphead=new ListNode (0);
        head=new ListNode(0);
        ListNode *tr=head;
        while(p){
            i=0;
            while(p&&i<k){p=p->next;i++;}
            if(i<k)break;
            for(int x=0;x<k;x++){
                r1=r1->next;
                r->next=tmphead->next;
                tmphead->next=r;
                r=r1;
            }
            tr->next=tmphead->next;
            tmphead->next=NULL;
            while(i--)tr=tr->next;
            
            
        }
        tr->next=r1;
        delete tmphead;
        return head->next;
        
    }
};

抱歉!评论已关闭.