双向链表 尾节点插入

import lombok.Data;

public class T {
    public static void main(String[] args) {
        DoubleLinkedList list = new DoubleLinkedList();
        list.addTail(1);
        list.addTail(2);
        list.addTail(3);
        
        System.out.println("尾节点: " + list.getTail().value); //3
        System.out.println("头节点: " + list.getHead().value); //1

        list.show();

    }
}

@Data
class DoubleLinkedList {
    Node head;
    Node tail;

    public void addTail(int value) {
        Node newNode = new Node(value);
        if (tail == null) {
            head = newNode;
            tail = newNode;
        } else {
            tail.next = newNode;
            newNode.prev = tail;
            //更新尾节点为当前新加入的节点
            tail = newNode;
        }
    }

    public void show() {
        System.out.print("遍历:");
        while (head != null) {
            System.out.print(head.value + ",");
            head = head.next;
        }
    }

}

class Node {
    int value;
    Node prev;
    Node next;

    Node(int value) {
        this.value = value;
    }
}
posted @ 2024-08-17 20:21  干饭达人GoodLucy  阅读(10)  评论(0编辑  收藏  举报