LintCode 36. 翻转链表 II

翻转链表中第m个节点到第n个节点的部分

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public 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) {
        // write your code here
        if (head == null) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        for (int i = 1; i < m; i++) {
            head = head.next;
        }

        ListNode premNode = head;
        ListNode mNode = head.next;
        ListNode nNode = mNode;
        ListNode postnNode = nNode.next;

        for (int i = m; i < n; i++) {
            ListNode tmpNode = postnNode.next;
            postnNode.next = nNode;
            nNode = postnNode;
            postnNode = tmpNode;
        }

        mNode.next = postnNode;
        premNode.next = nNode;

        return dummy.next;
    }
}

阅读更多

没有更多推荐了,返回首页