删除链表的中间节点和 a/b 处的节点

删除链表的中间节点和 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));
}

输出结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z6mejD14-1611842785727)(C:\Users\18801\AppData\Roaming\Typora\typora-user-images\image-20210128220009859.png)]

删除 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));
}

输出结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P6o6AAgp-1611842828430)(C:\Users\18801\AppData\Roaming\Typora\typora-user-images\image-20210128220533673.png)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值