【题目】删除链表的中间节点和a/b处的节点
public class DeleteMidAndabNode {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
// 删除中间节点
public static Node deleteMidNode(Node head) {
if (head == null || head.next == null) {
return head;
}
if (head.next.next == null) {
return head.next;
}
Node fast = head.next.next;
Node slow = head;
while (fast != null && fast.next.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
// 删除a/b处的节点
public static Node deleteMidNode(Node head, int a, int b) {
if (a > 1 || a > b) {
return head;
}
Node cur = head;
int n = 0;
while (cur != null) {
cur = cur.next;
n++;
}
n = (int) Math.ceil((a * n) / b);
if (n == 1) {
head = head.next;
}
if (n > 1) {
cur = head;
while (--n != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
}