C++ 中 K 個一組反轉節點


假設我們有一個連結串列,我們需要一次反轉連結串列的 k 個節點,並返回其修改後的列表。這裡 k 是一個正整數,並且小於或等於連結串列的長度。因此,如果節點數不是 k 的倍數,則最終剩餘的節點應該保持不變。

例如,如果連結串列是 [1,2,3,4,5,6,7] 且 k 為 3,則結果將為 [3,2,1,6,5,4,7]。

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個名為 solve() 的方法,它將接收連結串列的頭節點、partCount 和 k 作為引數。

  • 如果 partCount 為 0,則返回 head。

  • newHead := head, prev := null, x := k

  • 當 newHead 不為 null 且 x 不為 0 時

    • temp := newHead 的下一個節點,newHead 的下一個節點 := prev

    • prev := newHead,newHead := temp

  • head 的下一個節點 := solve(newHead, partCount – 1, k)

  • 返回 prev

  • 在主方法中執行以下操作:

  • 返回 solve(連結串列的頭節點, 列表長度 / k, k)

示例

讓我們來看下面的實現,以便更好地理解:

 線上演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
void print_vector(vector<vector<auto>> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head){
   ListNode *ptr = head;
   cout << "[";
   while(ptr){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
public:
   ListNode* solve(ListNode* head, int partitionCount, int k){
      if(partitionCount == 0)return head;
      ListNode *newHead = head;
      ListNode* prev = NULL;
      ListNode* temp;
      int x = k;
      while(newHead && x--){
         temp = newHead->next;
         newHead->next = prev;
         prev = newHead;
         newHead = temp;
      }
      head->next = solve(newHead, partitionCount - 1, k);
      return prev;
   }
   int calcLength(ListNode* head){
      int len = 0;
      ListNode* curr = head;
      while(curr){
         len++;
         curr = curr->next;
      }
      return len;
   }
   ListNode* reverseKGroup(ListNode* head, int k) {
      int length = calcLength(head);
      return solve(head, length / k, k);
   }
};
main(){
   vector<int> v = {1,2,3,4,5,6,7};
   ListNode *head = make_list(v);
   Solution ob;
   print_list(ob.reverseKGroup(head, 3));
}

輸入

1,2,3,4,5,6,7
3

輸出

[3, 2, 1, 6, 5, 4, 7, ]

更新於:2020年5月26日

瀏覽量:187

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告