您的位置:首页 > 其它

LeetCode Reverse Linked List II

2015-07-01 22:26 369 查看
Description:

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.
Solution:

只需要按照题目给出的模拟一下,链表的基本操作。注意+1 -1的区间操作。

import java.util.*;

public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n)
return head;

ListNode pre_node_m, next_node_n;
ListNode neoHead, neoTail, current, next;
if (m == 1) {
next_node_n = getNode(head, n + 1);
neoTail = neoHead = null;
current = head;
for (int i = m; i <= n; i++) {
next = current.next;
if (neoHead == null) {
neoHead = neoTail = current;
current.next = null;
} else {
current.next = neoHead;
neoHead = current;
}
current = next;
}
head = neoHead;
neoTail.next = next_node_n;
} else {
pre_node_m = getNode(head, m - 1);
next_node_n = getNode(head, n + 1);

current = pre_node_m.next;
neoTail = neoHead = null;
for (int i = m; i <= n; i++) {
next = current.next;
if (neoHead == null) {
neoHead = neoTail = current;
current.next = null;
} else {
current.next = neoHead;
neoHead = current;
}
current = next;
}

pre_node_m.next = neoHead;
neoTail.next = next_node_n;
}

return head;
}

ListNode getNode(ListNode head, int n) {
ListNode temp = head;
n--;
while (n > 0) {
temp = temp.next;
n--;
}
return temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: