双向循环链表,java例子

以下是一个使用Java实现的双向循环链表的示例:

class Node {
    int data;
    Node prev;
    Node next;

    public Node(int data) {
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}

class DoublyCircularLinkedList {
    private Node head;
    private Node tail;

    public DoublyCircularLinkedList() {
        this.head = null;
        this.tail = null;
    }

    public void insertAtFront(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            tail = newNode;
            newNode.next = newNode;
            newNode.prev = newNode;
        } else {
            newNode.next = head;
            newNode.prev = tail;
            head.prev = newNode;
            tail.next = newNode;
            head = newNode;
        }
    }

    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            tail = newNode;
            newNode.next = newNode;
            newNode.prev = newNode;
        } else {
            newNode.next = head;
            newNode.prev = tail;
            head.prev = newNode;
            tail.next = newNode;
            tail = newNode;
        }
    }

    public void display() {
        if (head == null) {
            System.out.println("Doubly circular linked list is empty.");
            return;
        }

        Node current = head;
        do {
            System.out.print(current.data + " ");
            current = current.next;
        } while (current != head);
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        DoublyCircularLinkedList dcll = new DoublyCircularLinkedList();

        dcll.insertAtFront(3);
        dcll.insertAtFront(2);
        dcll.insertAtFront(1);

        dcll.insertAtEnd(4);
        dcll.insertAtEnd(5);

        dcll.display();  // Output: 1 2 3 4 5
    }
}

在上述示例中,我们首先定义了一个Node类,用于表示双向循环链表中的节点。每个节点包含一个整数类型的data字段,以及指向前一个节点和后一个节点的prevnext指针。

然后,我们定义了DoublyCircularLinkedList类,作为双向循环链表的主要实现。该类包含headtail两个节点指针,用于表示链表的头部和尾部。

我们实现了insertAtFront方法和insertAtEnd方法,用于在链表的头部和尾部插入节点。在插入节点时,我们更新相应的指针以建立节点之间的双向循环连接。

最后,在Main类中,我们创建了一个双向循环链表对象dcll,并使用insertAtFrontinsertAtEnd方法插入了一些节点。然后调用display方法来打印出链表中的所有节点数据。

运行示例代码会输出:1 2 3 4 5,表示双向循环链表中节点的顺序。在循环链表中,我们可以从任

意一个节点出发,通过循环遍历访问到链表的所有节点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值