1. 程式人生 > >leetcode:k個一組翻轉連結串列

leetcode:k個一組翻轉連結串列

題目說明:給出一個連結串列,每 k 個節點一組進行翻轉,並返回翻轉後的連結串列。
k 是一個正整數,它的值小於或等於連結串列的長度。如果節點總數不是 k 的整數倍,那麼將最後剩餘節點保持原有順序。

示例 :

給定這個連結串列:1->2->3->4->5

當 k = 2 時,應當返回: 2->1->4->3->5

當 k = 3 時,應當返回: 3->2->1->4->5

說明 :

  • 你的演算法只能使用常數的額外空間。
  • 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
/**
 * 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(k<2)
            return head;
        ListNode*cur=head;
        ListNode*start=NULL;
        ListNode*pre=NULL;
        ListNode*next=NULL;
        int count=1;
        while(cur)
        {
            next=cur->next;
            if(count==k)
            {
                start=pre==NULL?head:pre->next;
                head=pre==NULL?cur:head;
                resign2(pre,start,cur,next);
                pre=start;
                count=0;
            }
            count++;
            cur=next;
        }
        return head;}
        void resign2(ListNode*left,ListNode*start,ListNode *end,ListNode *right)
        {
            ListNode*pre=start;
            ListNode*cur=start->next;
            ListNode*next=NULL;
            while(cur!=right)
            {
                next=cur->next;
                cur->next=pre;
                pre=cur;
                cur=next;
            }
            if(left!=NULL)
            {
                left->next=end;
            }
            start->next=right;
        }
 };