题目:Reverse Linked List II
难度:medium
问题描述:
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.
解题思路:没有对节点进行操作,直接对value进行了更改哈哈,有点偷鸡的味道~
具体代码如下:
public class m_92_ReverseLinkedListll {
public class ListNode{
int val;
ListNode next;
ListNode(int x){
val=x;
}
}
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n){
return head;
}
ListNode prenode=new ListNode(0);
prenode.next=head;
ListNode p=prenode;
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+1;i++){
t=t.next;
temp[i]=t.val;
}
t=p;
for(int i=0;i<n-m+1;i++){
t=t.next;
t.val=temp[n-m-i];
}
return head;
}
}