C++ 中 K 个一组反转节点
假设我们有一个链表,我们需要一次反转链表的 k 个节点,并返回其修改后的列表。这里 k 是一个正整数,并且小于或等于链表的长度。因此,如果节点数不是 k 的倍数,则最终剩余的节点应该保持不变。
例如,如果链表是 [1,2,3,4,5,6,7] 且 k 为 3,则结果将为 [3,2,1,6,5,4,7]。
为了解决这个问题,我们将遵循以下步骤:
定义一个名为 solve() 的方法,它将接收链表的头节点、partCount 和 k 作为参数。
如果 partCount 为 0,则返回 head。
newHead := head, prev := null, x := k
当 newHead 不为 null 且 x 不为 0 时
temp := newHead 的下一个节点,newHead 的下一个节点 := prev
prev := newHead,newHead := temp
head 的下一个节点 := solve(newHead, partCount – 1, k)
返回 prev
在主方法中执行以下操作:
返回 solve(链表的头节点, 列表长度 / k, k)
示例
让我们来看下面的实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
void print_vector(vector<vector<auto>> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
void print_list(ListNode *head){
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* solve(ListNode* head, int partitionCount, int k){
if(partitionCount == 0)return head;
ListNode *newHead = head;
ListNode* prev = NULL;
ListNode* temp;
int x = k;
while(newHead && x--){
temp = newHead->next;
newHead->next = prev;
prev = newHead;
newHead = temp;
}
head->next = solve(newHead, partitionCount - 1, k);
return prev;
}
int calcLength(ListNode* head){
int len = 0;
ListNode* curr = head;
while(curr){
len++;
curr = curr->next;
}
return len;
}
ListNode* reverseKGroup(ListNode* head, int k) {
int length = calcLength(head);
return solve(head, length / k, k);
}
};
main(){
vector<int> v = {1,2,3,4,5,6,7};
ListNode *head = make_list(v);
Solution ob;
print_list(ob.reverseKGroup(head, 3));
}输入
1,2,3,4,5,6,7 3
输出
[3, 2, 1, 6, 5, 4, 7, ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP