链表——环形链表

环形链表也叫循环单链表,操作原理和单链表差不多,只是最后一个节点不在指向空(null)而是头(head);

这里写图片描述

/*
 * 循环单链表
*/
class TestCLink{
    class Entry{//节点类
        int data;
        Entry next;

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

        public Entry(int data) {
            this.data = data;
            next = null;

        }
    }

    private Entry head = new Entry();
    /*
     * 头节点的初始化
    */
    public TestCLink() {
        this.head = new Entry();
        this.head.next = this.head;
    }
    /*
     * 头插法
    */
    public void insertHead(int val) {
        Entry entry = new Entry(val);
        entry.next = this.head.next;
        this.head.next = entry;
    }
    /*
     * 尾插法
    */
    public void insertTail(int val) {
        Entry entry = new Entry(val);
        Entry cur = this.head;         //找到尾巴
        while(cur.next != head) {
             cur = cur.next;
        }
        entry.next =  cur.next;
        cur.next = entry;
}

    /*
     * 删除一个元素
    */
    public void deleteEntry(int data) {//删除一个元素
        Entry p1 = head;                
        Entry p2 = head.next;         //前驱
/*      while(p2.data!=data){
            p1=p1.next;
            p2=p2.next;
        }
            p1.next=p2.next;
        }
*/  
        while(p2 != this.head) {
            if(p2.data == data) {
                p1.next = p2.next;
                p2 = p1.next;
            }else {
                p1 = p2;
                p2 = p2.next;
            }
        }
    }
     /*     
      * 得到链表长度  
       */   
    public int getlength() {
        Entry pwd = head;
        int length = 0;
        while(pwd.next != head) {
            length++;
            pwd = pwd.next;
        }
        return length;
    }

    public boolean isEmpty(){
        Entry cur = head;
        if(cur.next != this.head){
            return false;
        }else {
            return true;
        }
    }

    public void show() {
        Entry cur = this.head.next;
        while(cur != this.head) {
            System.out.print(cur.data+" ");
            cur = cur.next;
        }
        System.out.println();
    }
    }

public class TestDemo20 {

    public static void main(String[] args) {
        TestCLink t1=new TestCLink();
        for(int i=0;i<9;i++){
            t1.insertTail(i);
        }
        t1.show();
        t1.insertTail(5);
        t1.insertTail(5);
        t1.insertTail(5);
        t1.show();
        t1.deleteEntry(5);
        t1.show();
        int len=t1.getlength();
        System.out.println(len);

    }

}

猜你喜欢

转载自blog.csdn.net/qq2899349953/article/details/80220517