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;
}
}
本文介绍了如何在不使用额外内存的情况下,通过一次遍历链表,实现从指定位置m到n之间的节点进行反转。通过实例演示了具体操作步骤,并解释了相关注意事项。
496

被折叠的 条评论
为什么被折叠?



