25. K 个一组翻转链表
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode* reverseKGroup(ListNode* head, int k) 13 { 14 int len = 0; 15 for(ListNode* i = head;i != NULL;i = i->next) len ++; 16 17 ListNode* dummy = new ListNode(-1); 18 dummy->next = head; 19 ListNode* pre = dummy; 20 ListNode* cur = head; 21 22 for(int i = 0;i < len/k;i ++) 23 { 24 ListNode* new_head = NULL; 25 ListNode* first = cur; 26 int m = k; 27 while(m-- && cur) 28 { 29 ListNode* temp = cur->next; 30 cur->next = new_head; 31 new_head = cur; 32 cur = temp; 33 } 34 pre->next = new_head; 35 first->next = cur; 36 pre = first; 37 } 38 return dummy->next; 39 } 40 };
Mamba never out

浙公网安备 33010602011771号