leetcode:92. Reverse Linked List II(Java)解答
Posted boy_nihao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
以上是关于leetcode:92. Reverse Linked List II(Java)解答的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode92]Reverse Linked List II
#Leetcode# 92. Reverse Linked List II
Leetcode 92. Reverse Linked List II
leetcode.92. Reverse Linked List II