题目

/**
 * 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-pos<k)
                    break;
                
                if(pos!=0){
                    pre = end;
                }
                
                start = temp;
                end = temp;
                
                temp=temp->next;
                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; 
    }
};

相关文章:

  • 2021-10-03
  • 2021-11-29
  • 2021-11-14
  • 2022-12-23
  • 2021-10-20
  • 2021-10-29
  • 2021-10-11
猜你喜欢
  • 2021-07-26
  • 2021-04-30
  • 2022-01-15
  • 2021-05-18
  • 2021-11-17
  • 2022-02-17
相关资源
相似解决方案