您的位置:首页 > 编程语言 > Java开发

LeetCode | Reverse Linked List II

2014-03-04 23:23 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
.

Note:

Given m, n satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.
分析
这题就是细心了,由于题目保证了m、n的取值范围,代码里可以减少很多判断。

此外,为了代码简洁,可以在链表头部加个哨兵。

代码

public class ReverseLinkedListII {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
for (int i = 0; i < m - 1; ++i) {
p = p.next;
}
ListNode q = p.next;
for (int i = 0; i < n - m; ++i) {
ListNode temp = p.next;
p.next = q.next;
q.next = q.next.next;
p.next.next = temp;
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java LeetCode 链表