
在这个问题中,我们得到一个指向链表头部的指针和一个整数 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++免费学习笔记(深入)”;
以上就是使用C++按给定大小将双向链表分组反转的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号