愤怒中的小草

博客园 首页 新随笔 联系 订阅 管理

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

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

 

posted on 2019-04-25 20:15  愤怒中的小草  阅读(128)  评论(0编辑  收藏  举报