【Java数据结构】不带头单向循环链表

 

public class SingleLink {
    private static class Entry{
        private Entry next;
        private E value;
        public Entry(E value){
            this.value = value;
            next = this;
        }
    }
    private Entry headEntry;
    private Entry tailEntry;
    public SingleLink(){
    }
    public void addHead(T value){
        Entry newEntry = new Entry<>(value);
        if(headEntry == null){
            headEntry = newEntry;
            tailEntry = newEntry;
        }else{
            //1.
            newEntry.next = headEntry;
            //2
            headEntry = newEntry;
            //3
            tailEntry.next = headEntry;
        }
    }
    public void addTail(T value){
        Entry newEntry = new Entry<>(value);
        if(headEntry == null){
            headEntry = newEntry;
            tailEntry = newEntry;
        }else {
            tailEntry.next = newEntry;
            newEntry.next = headEntry;
            tailEntry = newEntry;
        }
    }
    public void deleteHead(){
        if(headEntry == null)
            return;
        //只有一个节点
        //防止内存泄漏
        headEntry.value = null;
        if(headEntry.next == headEntry){
            headEntry = null;
            tailEntry = null;
        }else {
            tailEntry.next = headEntry.next;
            //更新新头
            headEntry = headEntry.next;
        }
    }
    public void deleteTail(){}

    public void show(){
        if(headEntry == null){
            return;
        }
        Entry p = headEntry;
        do{
            System.out.print(p.value+" ");
            p=p.next;
        }while(p!=headEntry);
    }
}

 

 

你可能感兴趣的:(数据结构)