《程序员代码面试指南》第二章 链表问题 删除中间节点和a/b处节点

题目

例如 1-2-3-4 删除2,1-2-3-4-5 删除3
例如  a=1,b =2

java代码

/**
 * @Description:删除中间节点和a/b处节点
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 10:12
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter2_3 {

    //删除中间节点
    public Node removeMidNode(Node head) {
        if (head == null || head.next == null) {
            return null;
        }
        Node node1 = head;
        Node node2 = node1.next.next;
        //获取中间节点的前驱节点 ,因为让node2早走一步,当node2走完时,node1刚好是中间节点的前驱节点
        while (node2.next != null && node2.next.next != null) {
            node1 = node1.next;
            node2 = node2.next.next;
        }
        node1.next = node1.next.next;
        return head;
    }

    //删除a/b处的节点
    public Node removeNodeByRatio(Node head, int a, int b) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        int len = 0;//节点长度
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        //边界检查
        if (a < 0 || b <= 0) {
            return head;
        }
        int k = (int)Math.ceil((double)(a* len)/(double)b);
        //如果k==1 说明a/b处是头节点
        if (k == 1) {
            head = head.next;
        }
        if(k>1){
            cur =head;
            //提前减一,这样当k=1时,节点为 k处的前驱节点
            while (--k!=1){
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
        return head;
    }
    public void printLink(Node head) {
        System.out.println();
        while (head != null) {
            System.out.print(head.vlaue + " ");
            head = head.next;
        }
    }
    //测试
    public static void main(String[] args) {
        Chapter2_3 chapter = new Chapter2_3();
        Link link1= new Link();
        Link link2= new Link();
        //构造两个链表
        for (int i = 10; i >0 ; i--) {
            link1.add(i);
            link2.add(i);
        }
        chapter.printLink(link1.head);
        Node head1= chapter.removeMidNode(link1.head);
        chapter.printLink(head1);
        chapter.printLink(link2.head);
        Node head2=  chapter.removeNodeByRatio(link2.head,1,2);
        chapter.printLink(head2);

    }
}