leetcode25 K 个一组翻转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head==NULL)
            return NULL;
        if(k==1)
            return head;
        ListNode* ret=new ListNode(0);
        ret->next=head;
        ListNode* pre=ret; //pre ,前一组最后节点,pre->next当前组head
        ListNode* cur=head;
        ListNode* tail=ret;
        int count=0;
        while(true){
            count=0;
            tail=pre;
            while(tail!=NULL&&count<k){
                tail=tail->next;
                count++;
            }
            if(tail==NULL)
                break;
            while(pre->next!=tail){//一个个挂到tail后面
                cur=pre->next;
                pre->next=cur->next;
                cur->next=tail->next;
                tail->next=cur;
            }
            pre=head; //head当前组最后一个节点
            tail=head;
            head=pre->next;
        }
        return ret->next;
    }
};

猜你喜欢

转载自www.cnblogs.com/lqerio/p/11768648.html