泛型实现单链表

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

猜你喜欢

转载自blog.csdn.net/qq_37232304/article/details/80536520