25. K 个一组翻转链表

思路:
写一个反转子链表的函数,输入(head,tail),返回新的(head,tail).
每次先判断剩余长度是否足够k,找head和tail,并记录head的pre和tail的next,反转后指一指。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. pair<ListNode*,ListNode*> myReverse(ListNode* head, ListNode* tail){
  14. ListNode* pre = NULL;
  15. ListNode* now = head;
  16. while(pre!=tail){
  17. ListNode* nex = now->next;
  18. now->next = pre;
  19. pre = now;
  20. now = nex;
  21. }
  22. return make_pair(tail,head);
  23. }
  24. ListNode* reverseKGroup(ListNode* head, int k) {
  25. ListNode* dummy = new ListNode(0);
  26. dummy->next = head;
  27. ListNode* pre = dummy;
  28. while(head){
  29. ListNode* tail = head;
  30. for(int i=0;i<k-1;i++){
  31. tail = tail->next;
  32. if(tail==NULL){
  33. return dummy->next;
  34. }
  35. }
  36. ListNode* tailNext = tail->next;
  37. pair<ListNode*,ListNode*> p= myReverse(head,tail);
  38. ListNode* newHead = p.first;
  39. ListNode* newTail = p.second;
  40. pre->next = newHead;
  41. newTail->next = tailNext;
  42. pre = newTail;
  43. head = newTail->next;
  44. }
  45. return dummy->next;
  46. }
  47. };