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. public class Solution {
  4. public ListNode reverseBetween(ListNode head, int m, int n) {
  5. ListNode dummy = new ListNode(-1);
  6. dummy.next = head;
  7. ListNode prev = dummy;
  8. for (int i = 0; i < m-1; ++i)
  9. prev = prev.next;
  10. ListNode head2 = prev;
  11. prev = head2.next;
  12. ListNode cur = prev.next;
  13. for (int i = m; i < n; ++i) {
  14. prev.next = cur.next;
  15. cur.next = head2.next;
  16. head2.next = cur; // 头插法
  17. cur = prev.next;
  18. }
  19. return dummy.next;
  20. }
  21. };

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