双向链表Java实现

public class TwoWayLinkedList {
    private Node head; //表示链表的头部
    private Node tail; //表示链表的尾部
    private int length; //表示链表的长度
    private class Node {
        private Object data;
        private Node next;
        private Node prev;
        public Node(Object data) {
            this.data = data;
        }
    }
    public TwoWayLinkedList(){
        length = 0;
        head = null;
        tail = null;
    }
    //在链表的头部增加节点
    public void addHead(Object value) {
        Node newNode = new Node(value);
        if (length == 0) {
            head = newNode;
            tail = newNode;
            length++;
        }else {
            head.prev = newNode;
            newNode.next = head;
            head = newNode;
            length++;
        }
    }
    //在链表的尾部添加节点
    public void addTail(Object value) {
        Node newNode = new Node(value);
        if (length == 0) {
            head = newNode;
            tail = newNode;
            length++;
        } else  {
            newNode.prev = tail;
            tail.next = newNode;
            tail = newNode;
            length++;
        }
    }
    //删除链表的头节点
    public Node deleteHead () {
        Node temp = head;
        if (length != 0) {
            head = head.next;
            head.prev = null;
            length--;
            return temp;
        }else{
            return null;
        }
    }
    //删除链表的尾节点
    public Node deleteTail() {
        Node temp = tail;
        if (length != 0) {
            tail = tail.prev;
            tail.next = null;
            length--;
            return temp;
        } else {
            return null;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值