• 双端链表


    双端链表的概念:链表中保存着对最后一个节点引用的链表。

    1. 链表头部插入

    如果链表为空,要对链表尾部处理

    Element el = new Element(data);
    if(first == null){
       last = el;
    }
    el.next = first;
    first=el;
    

     

    2. 链表尾部插入

    如果链表为空,要对头节点进行处理

    Element el = new Element(data);
    if(first == null){
        first = el;
    }else{
        last.next = el;
    }
    last = el;
    

      

    3. 链表头部删除节点

    Element el = first;
    if(el.next != null){
          last = null;
    }
    first = el.next;
    

      

    code

    public class Element {
        public Object object;
        public Element next;
    
        public Element(Object object){
            this.object = object;
        }
    
        public void display(){
            System.out.println(this.object);
        }
    }
    public class DoubleLinkList {
        Element first;
        Element last;
        public DoubleLinkList(){
            first = null;
            last = null;
        }
    
        //从头结点开始插入
        public void addFirst(int data){
            Element el = new Element(data);
            if(first == null){
                last = el;
            }
            el.next = first;
            first=el;
        }
    
        //从尾结点开始插入
        public void addLast(int data){
            Element el = new Element(data);
            if(first == null){
                first = el;
            }else{
                last.next = el;
            }
            last = el;
        }
    
        //从头节点开始删除
        public void deleteFirst(){
            Element el = first;
            if(el.next != null){
                last = null;
            }
    
            first = el.next;
        }
    
        public void display(){
            Element element = first;
            while (element != null){
                element.display();
                element=element.next;
            }
        }
    }
    public class Demo {
        public static void main(String[] args){
            DoubleLinkList dll = new DoubleLinkList();
            dll.addFirst(1);
            dll.addFirst(2);
            dll.addFirst(3);
            dll.addFirst(4);
            dll.addLast(6);
            dll.addFirst(5);
            dll.addLast(8);
            dll.display();
            System.out.println("删除元素之后");
            dll.deleteFirst();
            dll.display();
        }
    }
    View Code
  • 相关阅读:
    中文排版指南
    HTTP返回码详解
    我的JS 类 写法
    【CodeForces】[630C]Lucky Numbers
    【CodeForces】[630C]Lucky Numbers
    【CodeForces】[630A]Again Twenty Five!
    【CodeForces】[630A]Again Twenty Five!
    【HPU】[1006]DNA
    【HPU】[1006]DNA
    【杭电】[3790]最短路径问题
  • 原文地址:https://www.cnblogs.com/mutong1228/p/10770683.html
Copyright © 2020-2023  润新知