第二章 链表问题
2.3 删除链表的中间节点和 a/b 处的节点
【题目】
给定链表的头节点 head,实现删除链表的中间节点的函数。
**进阶:**给定链表的头节点 head,整数 a 和 b没实现删除位于 a/b 出节点的函数。
【难度】
士 ★☆☆☆
【题解】
如果要删除一个节点,则需要找到待删除节点的前一个节点。
对于原问题,如果链表为空或者长度为 1,不需要调整。如果链表的长度大于 1,链表长度每增加 2,要删除的节点就向后移一个位置。
对于进阶问题,先计算 double r=((double)(a*n))/((double)b) 的值,然后 r 向上取整之后的整数值代表该删除的节点的位置。注意,如果 r≤0,不需要删除任何节点,如果 r>1,同样不需要删除任何节点。
【实现】
- RemoveMidNode.java
public class RemoveMidNode {
private static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
private Node head;
public RemoveMidNode(int[] arr) {
BuildLinkedList(arr);
}
private void BuildLinkedList(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
Node preNode = this.head = new Node(arr[0]);
for (int i = 1; i < arr.length; ++i) {
preNode = preNode.next = new Node(arr[i]);
}
}
public void removeMidNode() {
if (this.head == null || this.head.next == null) {
return;
}
if (this.head.next.next == null) {
this.head = this.head.next;
}
Node curNode = this.head.next.next;
Node preNode = this.head;
while (curNode.next != null && curNode.next.next != null) {
preNode = preNode.next;
curNode = curNode.next.next;
}
preNode.next = preNode.next.next;
}
}
- RemoveByRatio.java
public class RemoveByRatio {
private static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
private Node head;
public RemoveByRatio(int[] arr) {
BuildLinkedList(arr);
}
private void BuildLinkedList(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
Node preNode = this.head = new Node(arr[0]);
for (int i = 1; i < arr.length; ++i) {
preNode = preNode.next = new Node(arr[i]);
}
}
public void removeByRatio(int a, int b) {
if (a < 1 || a > b) {
return;
}
if (this.head == null || this.head.next == null) {
return;
}
int n = 1;
Node curNode = this.head;
while (curNode != null) {
++n;
curNode = curNode.next;
}
n = (int) Math.ceil((double) (a * n) / (double) b);
if (n == 1) {
this.head = this.head.next;
} else if (n > 1) {
curNode = this.head;
while (--n != 1) {
curNode = curNode.next;
}
curNode.next = curNode.next.next;
}
}
}
- Test.java
public class Test {
private RemoveMidNode mid;
private RemoveByRatio ratio;
public Test(int[] arr) {
this.mid = new RemoveMidNode(arr);
this.ratio = new RemoveByRatio(arr);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
Test test = new Test(arr);
test.mid.removeMidNode();
test.ratio.removeByRatio(3, 5);
}
}