java实现双向链表

链表可以抽象为若干相连起来的节点,其迭代只能顺着节点链依次访问。节点的组成简单的分为三个属性:节点的存储的值、前驱节点、后继节点。

简单的单向链表的实现中有个头节点(head),迭代都是从head元素开始。链表head节点的前驱节点和链表尾部元素的后继节点都为null。向链表添加元素时,新加入的元素标记为head节点,然后改变之前的head元素的前驱节点为当前head节点即可。当删除链表某个节点时也要根据具体删除节点的位置,改变删除节点前驱和后继节点的指向。以下是使用java语言实现的单向链表。

/**
 * desc : 链表的实现
 * Created by tiantian on 2018/9/2
 */
public class MyList {
    private Node head = null;

    public void insert(Object obj) {
        if (head == null) {
            head = new Node(obj);
            return;
        }
        
        Node node = new Node(obj);
        node.setNext(head);
        head.setPrev(node);
        head = node;
    }
    
    public Node delete(Object obj) {
        Node cur = head;
        
        Node deleted = null;
        if (head == null) { // 链表为空时
            return null;
        }
        
        if (head.next == null) { //只有一个元素时
            deleted = head;
            head = null;
            return deleted;
        }
        while (cur != null) {
            if (cur.getValue().equals(obj)) {
                deleted = cur;
                
                Node p = cur.getPrev();
                Node n = cur.getNext();
                if (p != null && n != null) { // 从链表中间删除时
                    p.setNext(n);
                    n.setPrev(p);
                } else if (n == null && p != null) { //删除尾部元素时
                    p.setNext(null);
                } else if (n != null && p == null) { //删除头部元素时
                    head = n;
                }
                break;
            }
            cur = cur.getNext();
        }

        cur = null;
        return deleted;
    }
    
    public static class Node {
        private Node prev = null;
        private Node next = null;
        private Object value;

        public Node(Object value) {
            this.value = value;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public Node getPrev() {
            return prev;
        }

        public void setPrev(Node prev) {
            this.prev = prev;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值