双向链表是一种数据结构,其中每个节点都包含两个指针,一个指向前一个节点,一个指向后一个节点。

以下是Java实现双向链表的示例代码:

public class DoubleLinkedList {
    private Node head;
    private Node tail;
    
    private class Node {
        private int data;
        private Node prev;
        private Node next;
        
        public Node(int data) {
            this.data = data;
        }
    }
    
    public void addToHead(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.next = head;
            head.prev = newNode;
            head = newNode;
        }
    }
    
    public void addToTail(int data) {
        Node newNode = new Node(data);
        if (tail == null) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.prev = tail;
            tail.next = newNode;
            tail = newNode;
        }
    }
    
    public void removeFromHead() {
        if (head == null) {
            return;
        }
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;
            head.prev = null;
        }
    }
    
    public void removeFromTail() {
        if (tail == null) {
            return;
        }
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            tail = tail.prev;
            tail.next = null;
        }
    }
    
    public void printList() {
        Node currentNode = head;
        while (currentNode != null) {
            System.out.print(currentNode.data + " ");
            currentNode = currentNode.next;
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        DoubleLinkedList list = new DoubleLinkedList();
        
        list.addToHead(1);
        list.addToHead(2);
        list.addToTail(3);
        
        list.printList();  // Output: 2 1 3
        
        list.removeFromHead();
        
        list.printList();  // Output: 1 3
        
        list.removeFromTail();
        
        list.printList();  // Output: 1
    }
}

在上面的示例代码中,addToHead方法将新节点添加到链表的头部,addToTail方法将新节点添加到链表的尾部,removeFromHead方法从链表的头部删除节点,removeFromTail方法从链表的尾部删除节点,printList方法用于打印链表中的所有节点

java实现双向链表

原文地址: https://www.cveoy.top/t/topic/ie0n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录