92:反转部分单向链表(reverse linked list(part))

问题

Reverse a linked list from position m to n. Do it in one-pass.
Example1:
    Input:1->2->3->4->5->NULL,m=2,n=4
    Output:1->4->3->2->5->NULL
Example2:
    Input:1->2->3->NULL,m=1,n=3
    Output:3->2->1->NULL

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        int length=0;

        ListNode node1=head;
        ListNode pre=null;
        ListNode end=null;

        while(node1!=null){
            length++;
            pre=length==m-1?node1:pre;
            end=length==n+1?node1:end;
            node1=node1.next;
        }

        if (m > n || m < 1 || n > length) {
            return head;
        }


        node1=pre==null?head:pre.next;
        ListNode node2=node1.next;
        node1.next=end;
        ListNode next=null;

        while (node2!=end){
            next=node2.next;
            node2.next=node1;
            node1=node2;
            node2=next;
        }


        if (pre!=null){
            pre.next=node1;
            return head;
        }

        return node1;

    }
}