Reverse Linked List II

    Example

    Given 1->2->3->4->5->NULL, m = 2 and n = 4, return
    1->4->3->2->5->NULL.

    Note

    Challenge

    Reverse it in-place and in one-pass

    题解

    1. 由于只翻转指定区域,分析受影响的区域为第m-1个和第n+1个节点
    2. 找到第m个节点,使用for循环n-m次,使用上题中的链表翻转方法
    3. 处理第m-1个和第n+1个节点
    4. 返回dummy->next
    1. * Definition for ListNode
    2. * public class ListNode {
    3. * int val;
    4. * ListNode next;
    5. * ListNode(int x) {
    6. * next = null;
    7. * }
    8. * }
    9. */
    10. public class Solution {
    11. /**
    12. * @param ListNode head is the head of the linked list
    13. * @oaram m and n
    14. */
    15. public ListNode reverseBetween(ListNode head, int m , int n) {
    16. ListNode dummy = new ListNode(0);
    17. dummy.next = head;
    18. // find the mth node
    19. ListNode premNode = dummy;
    20. for (int i = 1; i < m; i++) {
    21. premNode = premNode.next;
    22. }
    23. // reverse node between m and n
    24. while (curr != null && (m <= n)) {
    25. curr.next = prev;
    26. prev = curr;
    27. curr = nextNode;
    28. m++;
    29. }
    30. // join head and tail before m and after n
    31. premNode.next.next = curr;
    32. premNode.next = prev;
    33. return dummy.next;
    34. }
    35. }
    1. 处理异常
    2. 使用dummy辅助节点
    3. 找到premNode——m节点之前的一个节点
    4. 以nNode和postnNode进行遍历翻转,注意考虑在遍历到n之前postnNode可能为空
    5. 连接premNode和nNode,premNode->next = nNode;
    6. 连接mNode和postnNode,

    务必注意node 和node->next的区别!!,node指代节点,而node->next指代节点的下一连接。