LeetCode 92. 反转链表 II

LeetCode 92. 反转链表 II_第1张图片

思路:以题目链表示例

1.先头插如节点0

2.定位到节点2  前驱节点1

3.遍历从m 到 n翻转这一区域

4.最后将节点5追加到节点t(2)的后面

5.连接节点1和4

 

public static ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null)return head;
        ListNode insertNode = new ListNode(0);
        insertNode.next=head;
        ListNode t = insertNode;
        ListNode tpre = t;
        int index = 0;
        while (index < m){
            tpre = t;
            t =t.next;
            index++;
        }
        ListNode pre = tpre,cur = t;
        for (int i = m; i <= n; i++) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        t.next = cur;//5追加到2后面
        tpre.next = pre;//1.next=2;

        return insertNode.next;
    }

 

你可能感兴趣的:(算法,LeetCode,92.,反转链表,II)