您的位置:首页 > 其它

LeetCode OJ 92. Reverse Linked List II

2016-04-18 17:09 381 查看
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
.

相对于单纯的链表转置,这个问题需要把链表的一部分做反转。并要求就地反转而且只遍历一次。我的想法是吧链表看成3个部分:list1->list2->list3其中list2代表要反转的部分。我们先找到list2的开始,然后反转list2变为newlist2,然后把链表连接起来list1->newlist2->list3。实现起来还是比较简单的,但是要注意一些边界条件。这些边界条件通过m/n来控制。代码如下:

public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null || head.next==null || m==n || m>n) return head;
ListNode nhead = new ListNode(0);
nhead.next = head;
ListNode start = nhead;
ListNode end = null;
int count = 0;
while(start.next!=null && count<m-1){
count++;
start = start.next;
}
ListNode a = null;
ListNode b = start.next;
ListNode c = null;
end = b;
while(b!=null && count<n){
c = b.next;
b.next = a;
a = b;
b = c;
count++;
}
start.next = a;
end.next = b;
return nhead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: