1、题目描述
2、问题分析
这个题本质上还是按照链表翻转的思路来解,只是需要添加一些细节判断。
3、代码
1 class Solution { 2 public: 3 ListNode* reverseKGroup(ListNode* head, int k) { 4 if( !head || head->next == NULL || k <= 1 ){ 5 return head ; 6 } 7 8 ListNode dummy(0) ; 9 ListNode* d = &dummy ; 10 ListNode* p = head ; 11 12 while( p != NULL ){ 13 ListNode* pm = p; 14 int n = 1; 15 ListNode* nextNode ; 16 while( pm != NULL && n < k ){ 17 pm = pm->next ; 18 ++n; 19 } 20 if( pm != NULL ){ 21 nextNode = pm->next; 22 pm->next = NULL ; 23 24 d->next = reverseList( p ); 25 d = p; 26 p = nextNode ; // k % number of nodes == 0 ,out of while ; 27 28 }else{ 29 d->next = p; 30 break; 31 } 32 33 } 34 35 return dummy.next ; 36 37 } 38 39 ListNode* reverseList( ListNode* head ){ 40 if( !head || head->next == NULL ){ 41 return head; 42 } 43 ListNode* p = head ; 44 ListNode* q = head->next ; 45 head->next = NULL ; 46 while( p != NULL && q != NULL ){ 47 ListNode* tmp = q->next ; 48 q->next = p; 49 p = q ; 50 q = tmp ; 51 } 52 return p ; 53 54 } 55 };