lintcode 36.翻转链表II

翻转链表中的第m个到第n个结点,保证1<=m<=n<=链表长度。

思路:需要记录第m个结点的前一个节点,以及第n个结点的前一个结点,翻转m~n这部分,注意链表结点的衔接。

class Solution {
    /**
     * @param head: ListNode head is the head of the linked list 
     * @param m: An integer
     * @param n: An integer
     * @return: The head of the reversed ListNode
     */
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null)
            return head;
        ListNode prehead=new ListNode(0);//为了防止第1个元素也要翻转,在链表最前端增添了一个结点
        prehead.next=head;
        ListNode cur=prehead;
        int m1=m; int n1=n;//用一个m,n的副本,因为下面还需要用到m和n
        while(m1-->1){
            cur=cur.next;
            n1--;
        }
        ListNode before= cur;//before就是第m个结点的前一个结点
        while(n1-->0){
            cur=cur.next;
        }
        ListNode nNode=cur;//nNode就是第n个结点
        ListNode after=cur.next;//after就是第n个结点的后一个结点
        cur=before.next;//cur指向第m个结点,准备翻转
        before.next=nNode;//改变指向,第m个结点的前一个结点指向第n个结点
        //开始翻转m~n这部分结点
        ListNode next=null;
        ListNode pre=after;//第m个结点应该指向第n个结点的后一个结点
        for(int i=m;i<=n;i++){
            next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }        
        return prehead.next;
    }
}

猜你喜欢

转载自blog.csdn.net/thyzy120605/article/details/80724367