Java基础-模拟LinkedList的双向链表结构

package com.hspedu.collection_;


@SuppressWarnings({"all"})
public class Test514 {
    public static void main(String[] args) {
        // 模拟LinkedList的双向链表结构

        // 1、创建3个节点
        Node jack = new Node("Jack");
        Node tom = new Node("Tom");
        Node mary = new Node("Mary");

        // 2、节点的指向关系
        jack.next = tom;
        tom.next = mary;

        mary.prev = tom;
        tom.prev = jack;

        Node first = jack;
        Node last = mary;

        // 3、遍历双向链表的各个节点
        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.prev;
        }
    }
}


// 双向链表的节点
class Node {

    // 节点存放数据的data属性
    public Object data;

    // 指向前一个节点的next属性
    public Node next;

    // 指向后一个节点的prev属性
    public Node prev;

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

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                '}';
    }
}

 

posted @ 2022-03-23 01:22  柯南同学  阅读(17)  评论(0编辑  收藏  举报