第一步,找到将要翻转的位置,记录翻转部分前一个节点(prev)
第二步,翻转,记录翻转完成后这部分的首(reverseHead)和尾(reverseTail),以及翻转部分之后的一个节点(post)
第三部,将prev、reverseHead、reverseTail、post连接起来
代码:
1 ListNode *reverseBetween(ListNode *head, int m, int n) { 2 ListNode *node = head; 3 ListNode *prev = NULL; 4 ListNode *post = NULL; 5 ListNode *reverseHead = NULL; 6 ListNode *reverseTail = NULL; 7 int count = 1; 8 9 if (!head) 10 return NULL; 11 12 prev = NULL; 13 while (node && count < m ) { 14 prev = node; 15 node = node->next; 16 count++; 17 } 18 19 if (!node) 20 return head; 21 22 reverseTail = node; 23 post = node->next; 24 while (post && count < n) { 25 ListNode *postNext = post->next; 26 post->next = node; 27 node = post; 28 post = postNext; 29 count++; 30 } 31 reverseHead = node; 32 reverseTail->next = post; 33 34 if (!prev) 35 return reverseHead; 36 else { 37 prev->next = reverseHead; 38 return head; 39 } 40 }