雙向連結串列 尾節點插入

干饭达人GoodLucy發表於2024-08-17
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;
    }
}

相關文章