题目给你链表的头节点 head 每 k 个节点一组进行翻转请你返回修改后的链表。k 是一个正整数它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍那么请将最后剩余的节点保持原有顺序。你不能只是单纯的改变节点内部的值而是需要实际进行节点交换。示例 1输入head [1,2,3,4,5], k 2输出[2,1,4,3,5]示例 2输入head [1,2,3,4,5], k 3输出[3,2,1,4,5]思路先写翻转函数,然后断开k个链表,反转,然后连接左右的节点代码/** * Definitionforsingly-linked list. * 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: ListNode* reverseKGroup(ListNode* head, int k){ListNode *pumpynew ListNode(0);pumpy-nexthead;ListNode *startpumpy,*endpumpy;while(1){for(inti0;ikend;i)endend-next;if(!end)break;ListNode *nextHeadend-next;end-nextNULL;ListNode *currHeadstart-next;start-nextreverse(currHead);currHead-nextnextHead;startcurrHead;endcurrHead;}returnpumpy-next;}ListNode * reverse(ListNode *head){ListNode *preNULL,*currhead;while(curr){ListNode *nextcurr-next;curr-nextpre;precurr;currnext;}returnpre;}};感谢 睡不醒的鲤鱼 力扣每日一题
25 K 个一组翻转链表
题目给你链表的头节点 head 每 k 个节点一组进行翻转请你返回修改后的链表。k 是一个正整数它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍那么请将最后剩余的节点保持原有顺序。你不能只是单纯的改变节点内部的值而是需要实际进行节点交换。示例 1输入head [1,2,3,4,5], k 2输出[2,1,4,3,5]示例 2输入head [1,2,3,4,5], k 3输出[3,2,1,4,5]思路先写翻转函数,然后断开k个链表,反转,然后连接左右的节点代码/** * Definitionforsingly-linked list. * 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: ListNode* reverseKGroup(ListNode* head, int k){ListNode *pumpynew ListNode(0);pumpy-nexthead;ListNode *startpumpy,*endpumpy;while(1){for(inti0;ikend;i)endend-next;if(!end)break;ListNode *nextHeadend-next;end-nextNULL;ListNode *currHeadstart-next;start-nextreverse(currHead);currHead-nextnextHead;startcurrHead;endcurrHead;}returnpumpy-next;}ListNode * reverse(ListNode *head){ListNode *preNULL,*currhead;while(curr){ListNode *nextcurr-next;curr-nextpre;precurr;currnext;}returnpre;}};感谢 睡不醒的鲤鱼 力扣每日一题