LeetCode #25 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) {
        ListNode* ans=new ListNode(0);
        ListNode* lastend=new ListNode(0); //指向上一周期最后一个节点
        ListNode* pnext=new ListNode(0);  //下一节点
        ListNode* p=new ListNode(0);  //这一节点
        ListNode* q=new ListNode(0);  
        ListNode* begin=new ListNode(0);  
        ListNode* nextbegin=new ListNode(0);  //下一周期的开始
        ans->next=head;
        nextbegin=ans->next;
        lastend=ans;
        int i=0;
        while(nextbegin!=NULL){
            nextbegin=nextbegin->next;
            i++;
            if(i==k){
                p=lastend->next;
                begin=lastend->next;
                pnext=p->next;
                while(pnext!=nextbegin){
                    q=p;
                    p=pnext;
                    pnext=pnext->next;
                    p->next=q;
                }
                lastend->next=p;
                begin->next=nextbegin;
                lastend=begin;
                i=0;
            }
        }
        return ans->next;
    }
};

你可能感兴趣的:(LeetCode #25 K个一组翻转链表)