关闭

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

标签: leetcodejavaLinkedList
1673人阅读 评论(0) 收藏 举报
分类:

转载请注明出处: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;
    }
}
2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:148955次
    • 积分:2157
    • 等级:
    • 排名:第18374名
    • 原创:44篇
    • 转载:29篇
    • 译文:0篇
    • 评论:52条
    博客专栏
    友情链接
    最新评论