使用 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 和其他語言)編寫相同的程式。希望本文對您有所幫助。
廣告