链表——环形链表

环形链表也叫循环链表(可以是双链表、也可以是单链表),操作原理和单链表差不多,只是最后一个节点不在指向空(null)而是头(head),这里以单链表举例:

链表——环形链表_第1张图片

/**
 * @ClassName Annular
 * @Description 环形链表
 * @Author lzq
 * @Date 2018/11/3 20:46
 * @Version 1.0
 **/
public class Annular {
    /**
     * 节点类
     */
    class Entry {
        int data;
        Entry next;

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

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


    private Entry head = new Entry();  //头节点,列表首指针


    /**
     *  头结点的初始化
     */
    public Annular() {
        this.head = new Entry();
        this.head.next = this.head;
    }

    /**
     * 判断链表是否为空
     * @return
     */
    public boolean isEmpty(){
        Entry cur = head;
        if(cur.next != this.head){
            return false;
        }else {
            return true;
        }
    }


    /**
     * 头插法
     * @param val
     */
    public void insertHead(int val) {
        Entry entry = new Entry(val);
        if(this.head.next == null) {
            head.next = entry;
            entry.next = this.head;
            return;
        }
        entry.next = this.head.next;
        this.head.next = entry;
    }


    /**
     * 尾插法
     * @param val
     */
    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;
    }

    /**
     * 删除一个元素
     * @param data
     */
    public void deleteEntry(int data) {
        if(isEmpty()) {
            return ;
        }
        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;
            }
        }
    }

    /**
     * 得到链表的长度
     * @return
     */
    public int getlength() {
        if(isEmpty()) {
            return 0;
        }
        Entry pwd = head;
        int length = 0;
        while(pwd.next != head) {
            length++;
            pwd = pwd.next;
        }
        return length;
    }


    /**
     * 输出链表
     */
    public void show() {
        if(isEmpty()) {
            return ;
        }
        Entry cur = this.head.next;
        while(cur != this.head) {
            System.out.print(cur.data+" ");
            cur = cur.next;
        }
        System.out.println();
    }

}

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