LintCode 翻转链表 II

作者: 六尺帐篷 | 来源:发表于2017-03-07 19:28 被阅读68次

    题目

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

    注意事项
    m,n满足1 ≤ m ≤ n ≤ 链表长度

    代码

    /**
     * Definition for ListNode
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        /**
         * @param ListNode head is the head of the linked list 
         * @oaram m and n
         * @return: The head of the reversed ListNode
         */
        public ListNode reverseBetween(ListNode head, int m , int n) {
            // write your code
            if (m >= n || head == null) {
                return head;
            }
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
            
            for (int i = 1; i < m; i++) {
                if (head == null) {
                    return null;
                }
                head = head.next;
            }
            
            ListNode premNode = head;
            ListNode mNode = head.next;
            ListNode nNode = mNode, postnNode = mNode.next;
            for (int i = m; i < n; i++) {
                if (postnNode == null) {
                    return null;
                }
                ListNode temp = postnNode.next;
                postnNode.next = nNode;
                nNode = postnNode;
                postnNode = temp;
            }
            mNode.next = postnNode;
            premNode.next = nNode;
            
            return dummy.next;
        }
    }
    

    相关文章

      网友评论

        本文标题:LintCode 翻转链表 II

        本文链接:https://www.haomeiwen.com/subject/kkfvgttx.html