이중 연결리스트 데이터 구조 (E)

이중 연결리스트

포인터의 직접적인 후계자의 노드에 연결된 저장 구조에 대한 논의에 앞서 단지 뒤쪽에서 시작하여 시계 방향으로 다른 노드에 노드를 찾기 위해, 따라서 도메인을 나타냅니다. 바로 이전 노드를 찾으려면, 우리는에서 필요 헤더 시작. 즉, 하나의 링크 된리스트에서 실행 시간 NextElem는 O (1) PriorElem은 O (N)는 실행 시간이다. 단방향 단일 연결리스트의 이러한 단점을 극복하기 위해서는, 사용할 수있는 이중 연결리스트 .
이중 연결리스트의 노드 필드에 두 개의 포인터 번 직접 후속 포인트, 다른 시점 바로 이전 갖는다
같이 유사한 단일리스트, 이중 연결리스트 테이블이 순환 될 수있다,도 1의리스트의 두 개의 고리가있다.
그림 삽입 설명 여기

package main.com.cs.test;

public class DoublyLinkedList<T> {

    private int size;

    private Node<T> head;//链表的投节点

    private Node<T> tail;//链表的尾节点

    //构建一个null 链表
    public DoublyLinkedList() {
        this.head =this.tail= new Node<>();
    }


    private static class Node<T>{
        Node<T> Precursor;
        T data;
        Node<T> next;
        
        public Node(T data){
            this(data, null, null);
        }

        public Node(){
            this(null, null, null);
        }

        public String toString(){
            return this.data.toString();
        }

        Node(T data, Node<T> front, Node<T> next){
            this.Precursor = front;
            this.data = data;
            this.next = next;

        }


    }
    



    public boolean add(int index, T data) {
        if(index<0||data==null)
            throw new NullPointerException("index < 0 || data == null");

        int j = 0;
        Node<T> front = this.head;
        //查找要插入结点位置的前一个结点
        while (front.next != null && j < index) {
            j++;
            front = front.next;
        }

        //创建需要插入的结点,并让其前继指针指向front,后继指针指向front.next
        Node<T> q = new Node<T>(data, front, front.next);

        //空双链表插入和尾部插入,无需此操作
        if(front.next != null) {
            //更改front.next的前继指针
            front.next.Precursor = q;
        }
        //更改front的后继指针
        front.next = q;

        //在尾部插入时需要注意更新tail指向
        if(front==this.tail){
            this.tail=q;
        }
        return true;
    }



    public void printLinkList() {    //打印链表
        DoublyLinkedList.Node<T> curr = this.head;
        if (isEmpty()) {
            try {
                throw new Exception("linklist is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        while(curr != null){
            System.out.print(curr.data+" ");

            //判断如果 尾节点的 next 指向 头节点 那么就跳出循环
            if (curr.next == head){
                return;
            }
            curr = curr.next;

        }
    }
    public boolean isEmpty(){//判断链表是否为空
        return this.head == null;
    }

    public static void main(String[] args) {
        DoublyLinkedList<Integer> mylist = new DoublyLinkedList<Integer>();//构造一个空链表
        mylist.add(0,5);
        mylist.add(1,3);
        mylist.add(2,7);
        mylist.add(3,6);
        mylist.printLinkList();
    }
}

게시 69 개 원래 기사 · 원 찬양 6 · 전망 2501

추천

출처blog.csdn.net/qq_40539437/article/details/104002574