Java 实现无头双向链表的基本操作

无头双向链表的结构:
在这里插入图片描述

代码分析

节点结构

class Node {
   
    private int data;
    private Node next;
    private Node prev;

    public Node(int data) {
   
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}

	private Node head;  // 头节点
	private Node last;  // 尾节点
	public DoubleLinked() {
   
    this.head = null;
    this.last = null;
}

1. 头插法

/**
* 1.头插法
* @param data
*/
public void addFirst(int data) {
   
    Node node = new Node(data);
    if (this.head == null) {
   
        this.head = node;
        this.last = node;
    } else {
   
        node.next = this.head;
        this.head.prev = node;
        this.head = node;
    }
}

先判断链表是否为空,若为空,则直接插入,头节点和尾节点都直接指向新插入的元素;
若链表不为空,则把要插入节点的 next 指向链表头节点,头节点的 prev 指向新插入的节点,最后更新头节点为新插入节点,插入过程如下图所示:
在这里插入图片描述
在这里插入图片描述

2. 尾插法

/**
* 2.尾插法
* @param data
*/
public void addLast(int data) {
   
    Node node = new Node(data);
    if (this.head == null) {
   
        this.head = node;
        this.last = node;
    } else {
   
        this.last.next = node;
        node.prev = this.last;
        this.last = node;
    }
}

若链表为空,同头插法;
若链表不为空,则把链表尾节点的 next 指向要插入节点,要插入节点的 prev 指向链表尾节点,最后更新尾节点为新插入节点,插入过程如下图所示:
在这里插入图片描述
在这里插入图片描述

3. 查找是否包含关键字 key 在单链表中

// 查找
    private Node searchIndex(int index) {
   
        checkIndex(index);
        int count = 0;
        Node cur = this.head;
        while (count != index) {
   
            cur = cur.next;
            count++;
        }
        return cur;
    }

    // 合法性检查
    private void checkIndex(int index) {
   
        if (index < 0 || index > getLength()) {
   
            throw new IndexOutOfBoundsException("下标不合法!");
        }
    }

    /**
     * 3.任意位置插入,第一个数据节点为0号下标
     * @param index 插入位置
     * @param data 插入的值
     * @return true/false
     */
    @Override
    public boolean addIndex(int index, int data) {
   
        if (index ==0) {
   
            addFirst(data);
            return true;
        }

        if (index == getLength()) {
   
            addLast(data);
            return true;
        }

        // cur 指向index位置的节点
        Node cur = searchIndex(index);
        Node node = 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值