简单模拟一个双向链表

这篇博客介绍了如何创建一个简单的双向链表,包括从头到尾的遍历和从尾到头的遍历。此外,还展示了在已有的双向链表中如何方便地插入新的节点。通过示例代码,详细解释了双向链表操作的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class LinkedList01 {

    public static void main(String[] args) {
        //模拟一个简单的双向链表
        Node jack = new Node("jack");
        Node tom = new Node("tom");
        Node wyt = new Node("WYT");

        //连接三个节点形成双向链表
        jack.next=tom;
        tom.next=wyt;
        wyt.pre=tom;
        tom.pre=jack;
        Node first=jack;//让first引用指向jack,就是双向链表的头节点
        Node last=wyt;//让last引用指向wyt,就是双向链表的尾节点
        System.out.println("======演示从头到尾进行遍历========");
        /* //演示从头到尾进行遍历
        while (true){
            if (first==null){
                break;
            }
            System.out.println(first);
            first=first.next;
        }*/
        System.out.println("======演示从尾到头进行遍历========");

        //演示从尾到头进行遍历
        while (true){
            if (last==null){
                break;
            }
            System.out.println(last);
            last=last.pre;
        }
        //演示链表的添加对象/数据的方便
        //要求,是在tom----wyt插入对象smith
        //1.先创建一个Node节点 name是smith
        Node smith = new Node("smith");
        tom.next=smith;
        smith.next=wyt;
        wyt.pre=smith;
        smith.pre=tom;
        System.out.println("======演示从头到尾进行遍历========");
        //演示从头到尾进行遍历
        while (true){
            if (first==null){
                break;
            }
            System.out.println(first);
            first=first.next;
        }


    }
}
//定义一个Node类,Node对象表示双向链表的一个节点
class Node{
    public Object item;//真正存放数据
    public Node next;//指向后一个节点
    public Node pre;//指向前一个节点

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

    @Override
    public String toString() {
        return "Node name="+item
                ;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值