使用 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 函数将节点推入列表
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) { // 转到最后一个节点
      TMP = TMP->next;
   }
   TMP->next = new_node;
   new_node->prev = TMP;
   return head; // 返回指向头部的指针
}
// 打印给定列表的函数
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) { // 当我们的计数小于 k 时,我们只是简单地反转节点。
      newHead = CURRENT;
      TMP = CURRENT->prev;
      CURRENT->prev = CURRENT->next;
      CURRENT->next = TMP;
      CURRENT = CURRENT->prev;
      count++;
   }
   if (count >= k) {
      head->next = revK(CURRENT, k); // 现在,如果计数大于或等于
      //到 k 我们将第一个头连接到下一个头
   }
   return newHead;
}
int main() {
   Node* head;
   for (int i = 1; i <= 5; i++) {
      head = push(head, i);
   }
   cout << "原始清单: ";
   printDLL(head);
   cout << "\nModified List : ";
   int k = 3;
   head = revK(head, k);
   printDLL(head);
}
输出结果
原始清单: 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 和其他语言。我们希望这篇文章对您有所帮助。