您的位置:首页 > 其它

LeetCode2.2.2(Reverse Linked List II)

2015-08-29 09:34 316 查看
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->nullptr, m = 2 and n = 4,

return 1->4->3->2->5->nullptr.


Note: Given m, n satisfy the following condition: 1  m  n  length of list.

这道题思路不难,关键是要找准边界条件

public static void solution_2_2_2(Node head,int m,int k){
Node temp = head, mNode = null, kNode = null, mPre = null, h = null;
for (int i = 1; i <= k; i++) {
if (i == m - 1)
mPre = temp;
if (i == m)
mNode = temp;
if (i == k)
kNode = temp;
temp = temp.next;
}
// if(mPre!=null){
temp = mNode;
Node t = null, p = null;
for (int i = m; i <= k; i++) {
p = temp.next;
if (t == null) {
t = temp;
t.next = kNode.next;
} else {
temp.next = t;
t = temp;
}
if (i == k && mPre != null) {
mPre.next = t;
h = head;
}
if (i == k && mPre == null) {
h = t;
}
temp = p;
}
for (Node r = h; r != null; r = r.next) {
System.out.print(r.data + " ");
}

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