java链表模板

class MyList<T> {

    private int size = 0;
    // 头节点
    Node first = null;
    // 尾节点
    Node last = null;

    // 链表节点类(内部类)

    // 插入链表节点的方法
    // 参数i : 表示要插入的位置,当 i = -1 时新节点会被放置头位置,若 i = -2 时新节点会被放置至尾位置
    public void add(T data /* 传入数据 */) {
        // 创建新节点
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = null;
        // 一个元素都没有
        if (this.last == null) {  //没有元素
            this.first = newNode;
            this.last = newNode;
        } else { // 链表里有元素,在末尾新增一个
            
            this.last.next = newNode;
            this.last = newNode;
        }
        this.size++;
    }

    public void addList(MyList list) {
        if (list.size == 0) {
            return;
        }
        // 一个元素都没有
        if (this.last == null) {  //没有元素
            this.first = list.first;
            this.last = list.last;
        } else { // 有元素
            this.last.next = list.first;
            this.last = list.last;
        }
        this.size += list.size;
    }

    public void clear() {
        this.first = null;
        this.last = null;
        this.size = 0;
    }
}

class Node {
    // 下一个节点
    Node next;
    // 数据块
    Object data;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值