Total Accepted: 39279 Total Submissions: 150148My Submissions
Question Solution
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.
分析,顺序扫描链表,找出需要旋转的片段,旋转,关键点测试样例,全局旋转和部分旋转
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null)
return head;
else if(head.next==null)
return head;
else if(m<1)
m=1;
else if(m>=n)
return head;
ListNode x=new ListNode(0);
x.next=head;
ListNode y=x;
int i=1;
while(i<m)
{
y=y.next;
i++;
}
if(y.next==null)
return head;
else
{
int j=0;
ListNode e=y.next;
ListNode z=y.next;
ListNode v=z.next;
while(j<n-m+1&&v!=null)
{
z.next=y.next;
y.next=z;
z=v;
v=z.next;
j++;
}
if(j==n-m+1)
e.next=z;
else
{
z.next=y.next;
y.next=z;
e.next=v;
}
return x.next;
}
}
}
原文:http://7061299.blog.51cto.com/7051299/1652080