在for循环中创建双向链表

测试类

    @Test
    public void test() {
        Node head = new Node(0); // 创建头节点
        Node tail = null; // 定义尾节点
        Node temp = head; // 临时节点,相当于一个游标,初始化指向头节点

        for (int i = 1; i <= 10; i++) {
            Node newNode = new Node(i); // 新增节点
            temp.next = newNode; // 游标.next指向新节点
            newNode.pre = temp; // 新节点.pre指向当前游标

            tail = newNode; // 把新增节点作为尾节点
            temp = newNode; // 游标向后移动
        }

        // 已知头节点情况下,从前向后遍历
        StringJoiner headJoiner = new StringJoiner(" -> ");
        Node cursor = head;
        while (null != cursor) {
            headJoiner.add(String.valueOf(cursor.index));
            cursor = cursor.next; // 游标向后移动
        }
        System.out.println("head : " + headJoiner.toString()); // 打印

        // 已知尾节点情况下,从后向遍历
        StringJoiner tailJoiner = new StringJoiner(" -> ");
        cursor = tail;
        while (null != cursor) {
            tailJoiner.add(String.valueOf(cursor.index));
            cursor = cursor.pre; // 游标向前移动
        }
        System.out.println("tail : " + tailJoiner.toString()); // 打印
    }
}

// 自定义节点对象
class Node {
    int index;
    Node pre; // 前驱节点引用
    Node next; // 后继节点引用

    public Node(int index) {
        this.index = index;
    }
}

打印结果:

head : 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10
tail : 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0

原文地址:https://www.cnblogs.com/isawu/p/14999086.html