[leet code] 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->NULLm = 2 and n = 4,

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

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

=======================

Analysis:

One of the key tricks is to set up 2 pointers, distance between which equal to n-m.  Therefore, when the left pointer reached m position, the right pointer would reach n position as wee.  

After we got the node at position m and the node at position n, we move node at position m to the position after node n one by one, until all the nodes before node n processed. For example:

Original linked list:       1->2->3->4->5->6->7; m = 3, n =6

Step1:        1->2->4->5->6->3->7    

Step2:      1->2->5->6->4->3->7           

......

Result:      1->2->6->5->4->3->7

Note that pointer m is switching to right one by one in each step, but pointer n remains no change.

Finally, we need to consider about the case that reverse range started from the very beginning of the linked list.  In this case, we should return the pointer n rather than return the original head of the linked list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // init m node and n node
        ListNode mNode = head;
        ListNode nNode = head;
        
        // previous node of node m
        ListNode mPreNode = new ListNode(0);
        mPreNode.next = head;
        
        // set up the distance between node m and node n
        for (int i=0; i<n-m; i++) nNode = nNode.next;
        
        // locate node m and node n
        for (int i=0; i<m-1; i++){
            mPreNode = mNode;
            mNode = mNode.next;
            nNode = nNode.next;
        }
        
        // check if case of reversing from head
        boolean fromHead = false;
        if(mNode == head) fromHead = true;
        
        // reverse node range
        while(mNode!=nNode){
            ListNode temp = nNode.next;
            nNode.next = mNode;
            mPreNode.next = mNode.next;
            mNode.next = temp;
            mNode = mPreNode.next;
        }
        
        // case of reverse started from head
        if(fromHead == true) return nNode;
        
        // other cases
        return head;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值