手动实现循环单链表

/**
 * 循环单链表
 * @param <T>
 */
class Link3<T> {
    // 创建节点
    private static class Entry<T> {
        T date;
        Entry<T> next;

        public Entry(T date, Entry<T> next) {
            this.date = date;
            this.next = next;
        }
    }

    private static class Headentry<T> extends Entry<T> {
        int cnt;
       //给头结点中加上节点的个数
        public Headentry(T date, Entry<T> next, int cnt) {
            super(date, next);
            this.cnt = cnt;
        }
    }

    Headentry<T> head;
    //初始化设置头结点的下一个节点 为 头节点
    public Link3() {
        this.head = new Headentry<>(null, null, 0);
        this.head.next = this.head;
    }
//头插
    public void insertHead(T val) {
        Entry<T> node = new Entry<>(val, null);
        node.next = this.head.next;//将头结点于第一个节点的连接打断,将node.next放上去
        this.head.next = node;//然后将头结点的下一个元素置为node,此时头插完成
        this.head.cnt += 1;
    }
//尾插
    public void insertTail(T val){
        Entry<T> node = new Entry<>(val, null);//创建新的节点
        Entry<T> entry = head;//定义一个头结点

        while (entry.next != head){//遍历
            entry = entry.next;
        }
//        将最后一个元素与头结点的元素连接打断将node.naxt放进去
        node.next = entry.next;
        entry.next = node;//顺便将node放进去
        this.head.cnt +=1;
    }

//    删除元素
    public void remove(T val){
        Entry<T> pre = head;
        Entry<T> cur = head.next;
        while(cur != head){//细节
            if(cur.date == val){
                // val节点的删除
                pre.next = cur.next;
                //只删除第一个值尾val的节点
                cur = pre.next; // 删除链表中所有值为val的节点
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        this.head.cnt -= 1; // 更新头节点中链表节点的个数
    }

    public void show(){
        Entry<T> temp = this.head.next;
        while (temp != head) {
            System.out.print(temp.date + " ");
            temp=temp.next;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值