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->NULL, m = 2 and n = 4,

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

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

要将链表中间的数都翻转,显然就将链表分成3部分,将临界的地方都记录下来,遍历一次后再将临界的节点都连接好。
代码如下:

public ListNode reverseBetween(ListNode head, int m, int n) {
    ListNode instart=null,inend=null,outstart=null,outend=null;
    ListNode pre=null;
    int k=1;
    ListNode cur=head;
    while(cur!=null){
        if(k==m-1)
            outstart=cur;
        if(k==n+1)
            outend=cur;
        if(k==m){
            pre=cur;
            instart=cur;
        }
        if(k==n)
            inend=cur;
        if(k<=n&&k>m){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
            k++;
            continue ;
        }
        cur=cur.next;
        k++;
    }
    if(outstart==null){
        head=inend;
    }else{
        outstart.next=inend;
    }
    if(outend==null){
        instart.next=null;
    }else{
        instart.next=outend;
    }
    return head;
}

你可能感兴趣的:(java,LeetCode,链表)