Reverse Linked List II

描述

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:Given 1->2->3->4->5->nullptr, m = 2 and n = 4,

return 1->4->3->2->5->nullptr.

Note:Given m, n satisfy the following condition:1mn1 \leq m \leq n \leq length of list.

分析

这题非常繁琐,有很多边界检查,15分钟内做到bug free很有难度!

代码

  1. // Reverse Linked List II
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *reverseBetween(ListNode *head, int m, int n) {
  6. ListNode dummy(-1);
  7. dummy.next = head;
  8. ListNode *prev = &dummy;
  9. for (int i = 0; i < m-1; ++i)
  10. prev = prev->next;
  11. ListNode* const head2 = prev;
  12. prev = head2->next;
  13. ListNode *cur = prev->next;
  14. for (int i = m; i < n; ++i) {
  15. prev->next = cur->next;
  16. cur->next = head2->next;
  17. head2->next = cur; // 头插法
  18. cur = prev->next;
  19. }
  20. return dummy.next;
  21. }
  22. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/reverse-linked-list-ii.html