一、题目
问题1 给定链表的头节点head,实现删除链表的中间节点的函数。
问题分析:如果链表为空或者长度为1,不需调整,则直接返回;如果链表的长度为2,将头节点删除即可;如果大于等于3,则中间节点可取 (int) Math.ceil(tag / 2)。
removeMidNode 代码:
public 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;
int tag = 3;
while (cur.next != null) //求出节点数
{
cur = cur.next;
tag += 1;
}
int tag_mid = (int) Math.ceil(tag / 2);
tag = 1;
while (tag != tag_mid - 1) {
pre = pre.next;
tag += 1;
}
pre.next = pre.next.next;
return head;
}
问题2 给定链表的头节点head、整数a和b,实现删除位于a/b处节点的函数。
方法:先计算double r = ((double) (a * n)) / ((double) b)的值,然后 r 向上取整
之后的整数值代表该删除的节点是第几个节点。
removeByRatio 方法
public Node removeByRatio(Node head, int a, int b) {
if (a < 1 || a > b) {
return head;
}
int n = 0;
Node cur = head;
while (cur ! = null){
n++;
cur = cur.next;
}
n = (int) Math.ceil(((double) (a * n)) / (double) b);
// Math.ceil(0) =0 ; n == 0 表示 null ;
if (n == 1) {
head = head.next;
}
if (n > 1) {
cur = head;
while (--n != 1) {
cur = cur.next;
} //退出时 找到了mid的 前一个节点;
cur.next = cur.next.next;
}
return head;
}
3265




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



