反转列表I,Java实现如下:
public static Node reverse(Node root) {
Node head = null;
Node next = null;
Node curr = root;
while (curr != null) {
next = curr.next;
if (head == null) {
head = curr;
head.next = null;
} else {
curr.next = head;
head = curr;
}
curr = next;
}
return head;
}
private static class Node {
int val;
Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
public Node(int val) {
this(val, null);
}
}反转列表II,反转给定区域的列表。
例如,给定{1, 2, 3, 4, 5} ,反转第2个到第4个之间的所有元素为{1,4,3, 2, 5}。
解题思路如上,然需要小心不同越界。
public static Node reverse(Node root, int m, int n) {
if (root == null || m < 1 || n < m || size(root) < n)
throw new IllegalArgumentException(
"empty root or m < 1 or n < m or n > size(list)");
Node dumy = new Node(-1, root);
Node pre = dumy;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
} // the node right before the m-th node
Node head = null; // head for reverse
Node curr = pre.next;
Node tail = curr;
Node next = null;
for (int i = m; i <= n; i++) {
next = curr.next;
curr.next = head;
head = curr;
curr = next;
}
pre.next = head;
tail.next = curr; //attach the elements after n-th element
return dumy.next;
}

本文介绍两种Java实现的列表反转算法,一种是简单的整个列表反转,另一种是在指定范围内进行反转。通过具体的代码示例展示了如何操作单链表节点,并提供了解决方案来避免越界错误。
2814

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



