链表——双向链表

每个节点即有指向前一个节点的地址,还有指向后一个节点的地址;

这里写图片描述

/*
   双向循环链表
*/
class DoubeLink {
    class Entry {
        int data;
        Entry next;//后继
        Entry prio;//前驱 

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

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

    private Entry head = new Entry();


    /*
     * 头插法
    */
    public void inserthead(int val) {
        Entry entry = new Entry(val);
        entry.next = this.head.next; //后继
        entry.prio = this.head;      //前驱
        this.head.next = entry;
        if(entry.next  != null) {
            entry.next.prio =  entry;
        }
    }
    /*
     * 尾插法      
     */ 
    public void insertlast(int val){
        Entry entry = new Entry(val);
        Entry cur = this.head;
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = entry;
        entry.prio = cur;
    }
    /*
     * 删除元素
     * 第一种方法
    */
    public void deleteEntry(int val) {
        Entry cur = this.head.next;
        while(cur != null){
            if(cur.data == val){
                cur.prio.next = cur.next;
                if(cur.next != null) {   //没有这个删除最后一个有问题
                    cur.next.prio = cur.prio;
                }
            }
            cur = cur.next;
        }

    }
    /*
     * 删除元素
     * 第二种方法
    */
    public void sc(int val) {
        Entry p1 = head;
        Entry p2 = head.next;
        while(p2.next != null) {
            if(p2.data == val) {
                break;
            }
            p2 = p2.next;
            p1 = p1.next;
        }
        if(p2.next != null){  //删除尾巴用
            p1.next = p2.next;
            p1.next.prio = p1;
        }else {
            p1.next = null;
    }

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

public class shuangxiangxunhuan {

    public static void main(String[] args) {
        DoubeLink t1 = new DoubeLink();
             t1.insertlast(32); 
             t1.insertlast(25);
             t1.insertlast(23);
             t1.show();
    }

}

猜你喜欢

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