双向链表(一)

双向链表的定义和初始化

定义

双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继(next)和直接前驱(prev/prior)。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。如下图所示:

在这里插入图片描述

初始化

以java为例,对于双向链表的初始化,我们一般先定义出一个链表MyLinkedList(head,last),在定义节点node信息(next,prev,val)

public class MyLinkedList {
    public Node head;
    public Node last;
    public MyLinkedList(){
        head=last=null;
    }
public class Node {
    public Node prev;
    public Node next;
    public String val;

    public Node(String val){
        this.val=val;
    }
}

双向链表的创建(尾插)

同单链表相比,双链表仅是各节点多了一个用于指向直接前驱的指针域。因此,我们可以在单链表的基础轻松实现对双链表的创建。
需要注意的是,与单链表不同,双链表创建过程中,每创建一个新节点,都要与其前驱节点建立两次联系,分别是:

将新节点的 prev 指针指向直接前驱节点;
将直接前驱节点的 next 指针指向新节点;

以尾插为例:

public boolean add(String e){
        Node node=new Node(e);
        if(head==null)
            head = last = node;
        else {
            last.next=node;
            node.prev=last;
            last=last.next;
        }
        return true;
    }

双向链表指定位置插入

对于这种问题,我们需要分情况考虑:
1.指定位置(index)是否合法,即index不能为负数也不能大于链表节点个数(size);
2.链表为空的情况(size0);
3.插入位置为链表头或者链表尾(index
0,index==size);
4.其他任意位置插入。
具体分情况的代码示例如下:

public void add(int index,String e){
        if(index>size()||index<0)
            throw new ArithmeticException();
        else if (size()==0){
            Node node=new Node(e);
            head=last=node;
        }
        else if (index==0){
            Node node=new Node(e);
            node.next=head;
            head.prev=node;
            head=node;
        }
        else if (index == size()) {
            Node node=new Node(e);
            last.next=node;
            node.prev=last;
            last=last.next;
        }
        else {
            Node node=new Node(e);
            Node cur=head;
            for (int i=0;i<index-1;i++){
                cur=cur.next;
            }
            cur.next.prev=node;
            node.prev=cur;
            node.next=cur.next;
            cur.next=node;
        }
    }

运行结果如下:
在这里插入图片描述在第2个位置插入一个Q,结果如下

在这里插入图片描述

总结

双向链表不难,主要在于明白链表这种存储方式的特点以及节点间或者各引用间的逻辑关系,要保持思路清楚,以后再分享更多有关双向链表的知识吧~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值