使用 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 和其他语言)编写相同的程序。希望本文对您有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP