z_zhaojun的博客

机会只会留给有准备的人

leetcode:92. Reverse Linked List II(Java)解答

转载请注明出处:z_zhaojun的博客
原文地址:http://blog.csdn.net/u012975705/article/details/50408975
题目地址:https://leetcode.com/problems/reverse-linked-list-ii/

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.

解法(Java):

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode listNode = null;
        while (head != null) {
            ListNode node = new ListNode(head.val);
            if (listNode != null) {
                node.next = listNode;
            }
            listNode = node;
            head = head.next;
        }
        return listNode;
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode lNode;
        ListNode mNode;
        ListNode rNode;
        lNode = head;
        boolean hasL = true;
        if (m == 1) {
            hasL = false;
        }
        n -= m;
        while (--m > 1) {
            head = head.next;
        }
        if (hasL) {
            mNode = head.next;
        } else {
            mNode = head;
        }
        if (mNode == null) {
            return lNode;
        }
        ListNode temp;
        temp = mNode;
        while (n-- > 0) {
            temp = temp.next;
        }
        rNode = temp.next;
        temp.next = null;
        mNode = reverseList(mNode);
        if (hasL) {
            head.next = mNode;
        } else {
            head = mNode;
        }
        while (mNode.next != null) {
            mNode = mNode.next;
        }
        mNode.next = rNode;
        if (hasL) {
            return lNode;
        }
        return head;
    }
}
阅读更多
版权声明:本文为博主原创文章,转载请注明出处。博客首页:http://blog.csdn.net/u012975705。订阅:http://blog.csdn.net/u012975705/rss/list https://blog.csdn.net/u012975705/article/details/50408975
文章标签: leetcode java LinkedList
个人分类: LeetCode 算法相关
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭