双向链表的操作

    //基于双向链表算法的集合
    //建立一个内部类保存节点
    private Node first;//第一个节点对象
    private Node last;//最后一个节点对象
    private int size;//链表的节点对象的个数
    
    
    public void remove(Object ele) {
        //找到被删除的节点
        Node current = this.first;//第一个节点
        //遍历节点
        for (int i = 0; i < size; i++) {
            if(!current.ele.equals(ele)) {
                if(current.next==null) {
                    return;
                }
                current = current.next;
            }
        }
//        System.out.println(current.ele);
        //删除节点
        if(current==first) {
            this.first = current.next;
            this.first.prev = null;
        }else if(current==last) {
            this.last = current.prev;
            this.last.next = null;
        }else {
            current.prev.next = current.next;
            current.next.prev = current.prev; 
        }
        size--;//这个千万别忘了
    }
    
    
    public void addLast(Object ele) {
        Node node = new Node(ele);//需要保存的节点对象
        if(size==0) {//这个节点对象既是第一个也是最后一个
            this.first = node;
            this.last = node;
        }else {
            this.last.next = node;
            node.prev = this.last;
            this.last = node;
        }
        size++;
    }
    
    public void addFirst(Object ele) {
        Node node = new Node(ele);//需要保存的节点对象
        if(size==0) {//这个节点对象既是第一个也是最后一个
            this.first = node;
            this.last = node;
        }else {
            node.next = this.first;
            this.first.prev = node;
            this.first = node;
        }
        size++;
        }
    
    public String toString() {
        if(size==0) {
            return "[]";
        }
        Node current = this.first;//第一个节点
        StringBuilder str = new StringBuilder(size*2+1);
        str.append("[");
        for (int i = 0; i < size; i++) {
            str.append(current.ele);
            if(i!=size-1) {
                str.append(",");
            }else {
                str.append("]");
            }
            current = current.next;
        }
        return str.toString();
    }
    /*
     * 链表中的节点
     */
    class Node{
        Node prev;//上一个节点对象
        Node next;//下一个节点对象
        Object ele;//当前节点的元素
        public Node(Object ele) {
            this.ele = ele;//将元素赋值给该节点
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值