问题描述
给定链表的头节点head,实现删除链表的中间节点的方法;
若为偶数个:比如1234则删除节点2;
给定链表的头节点head,实现删除链表的a/b处节点的方法;
思路分析
删除中间节点
1个节点,不删除;
2个节点,删除节点1;
3个节点,删除节点2;
4个节点,删除节点2;
5个节点,删除节点3;
6个节点,删除节点3;
可以观察得出,在2个节点以上的情况下,后面每存在两个节点则被删除的节点往后移1;所以可以在k>2的时候进行判断:
while(current.next != null && current.next.next != null){
midNode = midNode.next;
current = current.next.next;
}
删除a/b处节点
给定整数a和b,实现删除位于a/b位置的节点;
打个比方:1->2->3->4->5 这个链表
如果在区间 (0,1/5], 删除节点1;
如果在区间 (0,2/5], 删除节点2;
如果在区间 (0,3/5], 删除节点3;
如果在区间 (0,4/5], 删除节点4;
如果在区间 (0,1], 删除节点5;
可以看出,是在r = ( a / b ) * n 然后将n向上取整得到的节点位置的方法;
所以根本是在于 求出 r的值并且运用Math.ceil()方法向上取整来得到准确的节点值,然后遍历链表删除即可;
代码实现1
package algorithm_zuochengyun;
public class CH2_03_removeByRatio {
public static Node removeByRatio(Node head, int a, int b) {
System.out.print("length = " + Node.getLen(head) + " ");
int length = Node.getLen(head);
int r = (int) Math.ceil((double) (length * a) / (double) b);
System.out.println("r = " + r);
Node current = head;
while (--r > 1) {
current = current.next;
}
current.next = current.next.next;
return head;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head = Node.init();
Node.Print(head);
removeByRatio(head, 5, 7);
Node.Print(head);
removeByRatio(head, 3, 6);
Node.Print(head);
}
}
实现结果1
代码实现2
package algorithm_zuochengyun;
import java.util.logging.Logger;
public class CH2_03_removeMidNode {
public static Node removeMidNode(Node head) {
if (head == null || head.next == null) {
System.out.println("null or 1 node .");
return head;
} else if (head.next != null && head.next.next == null) {
System.out.println("2 nodes .");
return head.next;
} else {
System.out.println("at least 3 nodes .");
// 起码三个 口(pre)口口(current),口口,口口
Node delete_preNode = head;
Node currentNode = head.next.next;
// 如果每当current后面都有两个几点结点存在那么被删除的结点则会往后推一个
// 如果不存在current后两个结点或者只存在curren.next那么仍然删除之前该删除的那个结点
while (currentNode.next != null && currentNode.next.next != null) {
currentNode = currentNode.next.next;
delete_preNode = delete_preNode.next;
}
delete_preNode.next = delete_preNode.next.next;
}
return head;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head1 = Node.init();
Node.Print(head1);
Node.Print(removeMidNode(head1));
}
}
实现结果2
问题总结
要学会从事件中寻找到规律
要透过描述看问题的本质要求的东西
Math类中取整的不同方法
- Math.floor() 向下取整
- Math.ceil() 向上取整
- Math.round() 四舍五入取整