首頁 > 後端開發 > C++ > 主體

使用C++按給定大小將雙向鍊錶分組反轉

王林
發布: 2023-09-04 09:49:06
轉載
1172 人瀏覽過

使用C++按給定大小將雙向鍊錶分組反轉

在這個問題中,我們得到一個指向鍊錶頭部的指標和一個整數 k。在大小為 k 的群組中,我們需要反轉鍊錶。例如 -

Input : 1 <-> 2 <-> 3 <-> 4 <-> 5 (doubly linked list), k = 3
Output : 3 <-> 2 <-> 1 <-> 5 <-> 4
登入後複製

尋找解決方案的方法

在這個問題中,我們將製定一個遞歸演算法來解決這個問題。在這種方法中,我們將使用遞歸並使用遞歸來解決問題。

範例

#include <iostream>
using namespace std;
struct Node {
   int data;
   Node *next, *prev;
};
// push function to push a node into the list
Node* push(Node* head, int data) {
   Node* new_node = new Node();
   new_node->data = data;
   new_node->next = NULL;
   Node* TMP = head;
   if (head == NULL) {
      new_node->prev = NULL;
      head = new_node;
      return head;
   }
   while (TMP->next != NULL) { // going to the last node
      TMP = TMP->next;
   }
   TMP->next = new_node;
   new_node->prev = TMP;
   return head; // return pointer to head
}
// function to print given list
void printDLL(Node* head) {
   while (head != NULL) {
   cout << head->data << " ";
   head = head->next;
}
cout << endl;
}
Node* revK(Node* head, int k) {
   if (!head)
      return NULL;
   head->prev = NULL;
   Node *TMP, *CURRENT = head, *newHead;
   int count = 0;
   while (CURRENT != NULL && count < k) { // while our count is less than k we simply reverse                                                 the nodes.
      newHead = CURRENT;
      TMP = CURRENT->prev;
      CURRENT->prev = CURRENT->next;
      CURRENT->next = TMP;
      CURRENT = CURRENT->prev;
      count++;
   }
   if (count >= k) {
      head->next = revK(CURRENT, k); // now when if the count is greater or equal
      //to k we connect first head to next head
   }
   return newHead;
}
int main() {
   Node* head;
   for (int i = 1; i <= 5; i++) {
      head = push(head, i);
   }
   cout << "Original List : ";
   printDLL(head);
   cout << "\nModified List : ";
   int k = 3;
   head = revK(head, k);
   printDLL(head);
}

登入後複製

輸出

Original List : 1 2 3 4 5
Modified List : 3 2 1 5 4
登入後複製

上述程式碼的解釋

在這個方法中,我們遍歷列表並遍歷直到計數小於 k。我們進行遞歸調用,將該值賦予head -> next( 這裡我們只是在遍歷時反轉列表,但是當達到k 時,我們需要使head 指向另一個列表的第k 個元素,例如,如果我們的列表是1 2 3 4 5,我們的k 是3,我們將中間元素反轉為3 2 1,但現在我們需要1 指向4,因為該元素也將被反轉,所以這就是我們使用的原因遞歸調用並進行額外的if 語句。)。

結論

在本文中,我們解決了使用 遞歸。我們也學習了這個問題的C 程式以及我們解決的完整方法。我們可以用其他語言像是C、java、python等語言來寫同樣的程式。我們希望這篇文章對您有幫助。

以上是使用C++按給定大小將雙向鍊錶分組反轉的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!