- 给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。(24题的升级版)
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
}
};
解
private ListNode reverseTopN(ListNode head, int n) {
ListNode prev = null;
ListNode cur = head;
for(int num = 0; num < n; num++){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
作者:hardcore-aryabhata
链接:https://leetcode.cn/problems/reverse-nodes-in-k-group/solution/dong-hua-yan-shi-di-gui-25-kge-yi-zu-fan-y6hv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public ListNode reverseKGroup(ListNode head, int k) {
ListNode nextHead = head;
int remainNum = 0;
while (remainNum < k){
if (nextHead == null) {
return head;
}
remainNum++;
nextHead = nextHead.next;
}
ListNode subList = reverseKGroup(nextHead,k);
ListNode newHead = reverseTopN(head, k);
head.next = subList;
return newHead;
}
作者:hardcore-aryabhata
链接:https://leetcode.cn/problems/reverse-nodes-in-k-group/solution/dong-hua-yan-shi-di-gui-25-kge-yi-zu-fan-y6hv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
完整代码
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
static ListNode* reverseK(ListNode* head, int k){// 因为调用的时候 Solution::reverseKGroup 直接与类关联 加上了static
ListNode* pre = nullptr;
ListNode* next = nullptr;
ListNode* cur = head;
for(int i=0;i<k;i++){
next = cur->next;
cur->next = pre;
pre = cur;// pre->next = next;(pre空没有next),只有一个指针翻转即可
cur = next;// pre 和 cur 全部后移即可
}
return pre;
}
static ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* orihead = head;
for(int i=0;i<k;i++){
if(head!= nullptr){ head = head->next; }else{return orihead;}
}
ListNode* sublist = reverseKGroup( head, k);//返回子部分
ListNode* newhead = Solution::reverseK( orihead, k);
orihead->next =sublist;
return newhead;
}
};
using namespace std;
int main() {
std::cout << "Hello, World!" << std::endl;
int a[]={1,2,3,4,5,6};
//int a[]={1,2};
std::vector<ListNode*> b;
for(int i=0;i<(sizeof(a) / sizeof(a[0]) );i++){
ListNode* node = new ListNode(a[i]);
b.push_back(node);
}
for(int i=0;i<(sizeof(a) / sizeof(a[0]) )-1;i++){
b[i]->next =b[i+1];//std::cout<< b[i]->val << b[i+1]->val <<std::endl;
}
ListNode* res = Solution::reverseKGroup(b[0],2);
while(res != nullptr){
cout<< res->val << endl;
res = res->next;
}
return 0;
}