《程序员代码面试指南》第二章 链表问题 在单链表和双链表中删除倒数第K个节点

题目

在单链表和双链表中删除倒数第K个节点

java代码

/**
 * @Description:在单链表和双链表中删除倒数第K个节点
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 9:14
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter2_2 {
    public Node removeKNode(Node head, int k) {
        if (head == null || k < 1) {
            return null;
        }
        Node cur = head;
        while (cur != null) {
            k--;
            cur = cur.next;
        }
        //此时k==0,说明原始K等于链表长度;
        if (k == 0) {
            head = head.next;
            return head;
        }
        if (k < 0) {
            cur = head;
            while (++k != 0) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
        return head;
    }

    public DoubleNode removeKDoubleNode(DoubleNode head, int k) {
        if (head == null || k < 1) {
            return null;
        }
        DoubleNode cur = head;
        while (cur != null) {
            k--;
            cur = cur.next;
        }
        //此时k==0,说明原始K等于链表长度;
        if (k == 0) {
            head = head.next;
            head.pre = null;
            return head;
        }
        if (k < 0) {
            cur = head;
            while (++k != 0) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
            if (cur.next.next != null) {
                cur.next.next.pre = cur;
            }
        }
        return head;
    }

    public void printLink(Node head) {
        System.out.println();
        while (head != null) {
            System.out.print(head.vlaue + " ");
            head = head.next;
        }
    }

    public void printDLink(DoubleNode head) {
        System.out.println();
        while (head != null) {
            System.out.print(head.vlaue + " ");
            head = head.next;
        }
    }

    //测试
    public static void main(String[] args) {
        Chapter2_2 chapter = new Chapter2_2();
        Link link1 = new Link();//单链表
        Link link2 = new Link();//双链表

        //构造链表
        for (int i = 10; i > 0; i--) {
            link1.add(i);
            link2.addDoubleNode(i);
        }
        chapter.printLink(link1.head);
        Node head = chapter.removeKNode(link1.head, 5);
        chapter.printLink(head);
        chapter.printDLink(link2.dhead);
        DoubleNode dhead = chapter.removeKDoubleNode(link2.dhead, 5);
        chapter.printDLink(dhead);

    }
}