LeetCode 25 Reverse Nodes in k-Group

题目

/**
 * 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) {
        
        
        int num=0;
        ListNode* temp = head;
        while(temp!=NULL)
        {
            num++;
            temp = temp->next;
        }
        
        if(k>num||k==1)
            return head;
        
        ListNode* start;
        ListNode* end;
        ListNode* pre;
        ListNode* res;
        
        pre = res = new ListNode(0);
        temp = head;
        int pos=0;
        while(temp!=NULL)
        {

            if((pos==0 || pos%k==0))
            {
                if(num-posnext;
                pos++;
            }
            else
            {
                ListNode* term = temp;
                temp = temp->next;
                end->next = term->next;
                term->next = start;
                pre->next = term;
                start=term;
                //pre->next = start;
                
                
                pos++;
            }
        }
        return res->next; 
    }
};

你可能感兴趣的:(LeetCode 25 Reverse Nodes in k-Group)