25. K 个一组翻转链表
思路:
写一个反转子链表的函数,输入(head,tail),返回新的(head,tail).
每次先判断剩余长度是否足够k,找head和tail,并记录head的pre和tail的next,反转后指一指。
/*** Definition for singly-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:pair<ListNode*,ListNode*> myReverse(ListNode* head, ListNode* tail){ListNode* pre = NULL;ListNode* now = head;while(pre!=tail){ListNode* nex = now->next;now->next = pre;pre = now;now = nex;}return make_pair(tail,head);}ListNode* reverseKGroup(ListNode* head, int k) {ListNode* dummy = new ListNode(0);dummy->next = head;ListNode* pre = dummy;while(head){ListNode* tail = head;for(int i=0;i<k-1;i++){tail = tail->next;if(tail==NULL){return dummy->next;}}ListNode* tailNext = tail->next;pair<ListNode*,ListNode*> p= myReverse(head,tail);ListNode* newHead = p.first;ListNode* newTail = p.second;pre->next = newHead;newTail->next = tailNext;pre = newTail;head = newTail->next;}return dummy->next;}};
