删除链表的中间节点和 a/b 处的节点
首先是删除中间节点
链表长度为n,
n = 0, 不删除;
n = 1, 不删除;
n = 2, 删除第 1 个节点;
n = 3, 删除第 2 个节点;
n = 4, 删除第 2个节点;
n = 5, 删除第 3 个节点;
n = 6, 删除第 3 个节点;
n = 7, 删除第 4 个节点;
总结:从链表长度大于等于2时,每增加两个节点,删除节点后移一位。
具体代码
public static Node removeMidNode(Node head) {
if (head == null || head.next == null) {
return head;
}
if (head.next.next == null) {
return head.next;
}
Node pre = head;
Node cur = head.next.next;
while (cur.next != null && cur.next.next != null) {
pre = pre.next;
cur = cur.next.next;
}
pre.next = pre.next.next;
return head;
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.value + " ");
head = head.next;
}
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(6);
head1.next.next.next.next = new Node(7);
head1.next.next.next.next.next = new Node(3);
print(removeMidNode(head1));
}
输出结果
删除 a/b 处的节点
比如:a=2 b=5 n=6,那么删除2/5处的节点就是(2/5)*6=2.4处的节点,凡是出现小数则向上取整,则删除的是第三个节点。
具体代码
public static Node removeByRatio(Node head, int a, int b) {
if (a > b || head == null) {
return head;
}
int n = 0;
Node cur = head;
//算出链表的长度
while (cur != null) {
n++;
cur = cur.next;
}
n = (int) Math.ceil(((double) (a*n))/((double)b));
if(n==1){
head = head.next;
}
if(n>1){
cur = head;
while (--n!=1){
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(6);
head1.next.next.next.next = new Node(7);
head1.next.next.next.next.next = new Node(3);
print(removeByRatio(head1,3,5));
}
输出结果