删除a/b处的节点

链表:1->2->3->4->5,假如a/b的值为r。

如果r等于0,不删除任何节点;
如果r在区间(0, 1/5]上,删除节点1;
如果r在区间(1/5, 2/5]上,删除节点2;
如果r在区间(2/5, 3/5]上,删除节点3;
如果r在区间(3/5, 4/5]上,删除节点4;
如果r在区间(4/5, 1]上,删除节点5;
如果r大于1,不删除任何节点;

删除链表的问题一般需要分情况讨论,1)删除头节点;2)删除非头节点。

package 链表问题;

/**
 * 〈一句话功能简述〉<br> 
 * 〈删除链表的中间节点和a/b处的节点〉
 *
 * @author 我们
 * @create 2021/1/27
 * @since 1.0.0
 */
class Node{
    public int value;
    public Node next;
    public Node(int value){
        this.value = value;
    }
}
public class Solution3 {
    public static 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;
        }
        // (a / b) * n
        n = (int) Math.ceil(((double)(a * n)) / (double) b);
        // 删除头节点--头节点改变
        if (n == 1){
            return head.next;
        }
        // 删除非头节点
        if (n > 1){
            cur = head; // 重置当前节点
            while(--n != 1){ // 找到要删除的前一个节点[所以是--n != 1]
                cur = cur.next; // 找到要删除的前一个节点
            }
            cur.next = cur.next.next; // 删除这个节点
        }
        return head;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node (5);

        removeByRatio(head, 2, 5);
        while(head != null){
            System.out.println(head.value);
            head = head.next;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39443483/article/details/113320862