您的位置:首页 > 其它

leetcode_92_Reverse Linked List II

2015-02-04 21:01 405 查看

描述:

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==1和m>1的情况,然后就是围绕这两种情况展开讨论,删除后面的结点,然后将后面的结点添加到前面,一次搞定,bravo!

代码:

public ListNode reverseBetween(ListNode head, int m, int n) {
if (head==null) {
return null;
}
ListNode p =head,q=head,temp=null;
int i=0;
for(i=0;i<m-1;i++)
q=q.next;
for(i=0;i<m-2;i++)
p=p.next;
if(m==1)
{
for(i=0;i<n-m;i++)
{
//delete the node in the list
temp=q.next;
q.next=temp.next;
//insert the node in the list
temp.next=p;
p=temp;
}
head=p;
}else
{
for(i=0;i<n-m;i++)
{
//delete the node in the list
temp=q.next;
q.next=temp.next;
//insert the node in the list
temp.next=p.next;
p.next=temp;
}
}
return head;
}


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: