泛型实现单链表

class testlink1<T>{
    class Entry<T>{
        T data;
        Entry<T> next;
        public Entry(){
            this.data=null;
            this.next=null;

        }
        public Entry(T val){
            this.data=val;
            this.next=null;

        }
    }
    Entry <T>head;
    public testlink1(){
        this.head=new Entry<T>();
    }
    /*头插法
     * */
    public void inserthead(T val){
        Entry<T> entry =new Entry<T>(val);
        entry.next=this.head.next;
        this.head.next=entry;

    }
    /*尾插法
     * */
    public void inserttail(T val){
        Entry<T> cur=this.head;
        while(cur.next!=null){
            cur=cur.next;

        }
        Entry<T> entry =new Entry<T>(val);
        entry.next=cur.next;
        cur.next=entry;

    }
    /*
     * 打印单链表
     * */
    public void show(){
        Entry<T> cur=this.head.next;
        while(cur!=null){
            System.out.println(cur.data);
            cur=cur.next;

        }
    }
    /*
     * 删除单链表中的所有某个元素
     * */
    public  void delectall(T val){
        Entry<T> t1=this.head.next;
        Entry<T> t2=this.head;
        while(t1!=null){
            if(t1.data==val){
                t2.next=t1.next;
                t1=t2.next;
            }
            else{
                t1=t1.next;
                t2=t2.next;
            }


        }

    }

}

调试代码

public class testlink {

    public static void main(String[] args) {
        testlink1<Integer> t1=new testlink1<Integer>(); 
        t1.inserthead(1);
        t1.inserthead(5);       
        t1.inserttail(6);
        t1.show();
        System.out.println("===========");
        testlink1<String> t2=new testlink1<String>(); 
        t2.inserthead("b");
        t2.inserthead("a");
        t2.inserttail("c");
        t2.inserttail("c");
        t2.show();
        t2.delectall("c");
        System.out.println("===========");
        t2.show();
    }

}

运行结果

5
1
6
===========
a
b
c
c
===========
a
b
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值