双链表的增删改查

双链表的增删改查

/**
 * 双链表增删改查
 */
class DoubleLinkedList {
    HeroNode head = new HeroNode();

    /**
     * 添加节点
     * @param heroNode
     */
    public void add(HeroNode heroNode) {
        HeroNode temp = head;

        while (true) {
            if (temp.next == null) {
                temp.next = heroNode;
                heroNode.pre = temp;
                break;
            }
            temp = temp.next;
        }

    }

    /**
     * 双链表可以自我删除
     * @param heroNode
     */
    public void del(HeroNode heroNode) {
        if (head.next == null) {
            throw new NullPointerException("链表为空,不可删除");
        }

        HeroNode temp = head.next;
        while (true) {
            if (temp == null) {
                throw new NullPointerException("未找到该节点");
            }
            if (temp.no == heroNode.no) {
                // 避免是最后一个节点
                temp.pre.next = temp.next;
                if (temp.next != null) {
                    temp.next.pre = temp.pre;
                }
                return;
            }
            temp = temp.next;
        }
    }

    /**
     * 修改节点
     * @param heroNode
     */
    public void update(HeroNode heroNode) {
        if (head.next == null) {
            throw new NullPointerException("链表为空,不可修改");
        }

        HeroNode temp = head.next;
        while (true) {
            if (temp == null) {
                throw new NullPointerException("未找到该节点");
            }
            if (temp.no == heroNode.no) {
                temp.name = heroNode.name;
                break;
            }
            temp = temp.next;
        }
    }

    /**
     * 遍历双链表
     */
    public void show() {
        if (head.next == null) {
            throw new NullPointerException("链表为空,不可遍历");
        }

        HeroNode temp = head.next;
        while (true) {
            if (temp == null) {
                break;
            }

            System.out.println(temp);
            temp = temp.next;
        }
    }

    /**
     * 静态内部类双链表节点
     */
    static class HeroNode {
        public int no;
        public String name;
        public HeroNode next;
        public HeroNode pre;

        public HeroNode() {
        }

        public HeroNode(int no, String name) {
            this.no = no;
            this.name = name;
        }

        @Override
        public String toString() {
            return "HeroNode{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值