https://leetcode.com/problems/reverse-linked-list-ii/#/description
问题描述:
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.
思路解析:
用指针定位到m之前,将m~n的值存储到数组中,只将值进行转置。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n)return head;
ListNode pre=new ListNode(0);
pre.next=head;
ListNode p=pre;
for(int i=1;i<m;i++){
p=p.next;
}
ListNode t=p;
int[] temp=new int[n-m+1];
for(int i=0;i<=n-m;i++)
{
t=t.next;
temp[i]=t.val;
}
t=p;
for(int i=0;i<=n-m;i++)
{
t=t.next;
t.val=temp[n-m-i];
}
return pre.next;
}
}