Java教程

Java创建N个节点的循环链接列表并计算节点数

在此程序中,我们必须找出循环链接中存在的节点数清单。我们首先创建循环链接列表,然后遍历列表并将变量'count'加1。

算法

定义一个代表列表中节点的Node类。它有两个属性数据,下一个将指向下一个节点。 定义另一个用于创建循环链表的类,它具有两个节点: head和tail。它有两种方法: add()和display()。 add()会将节点添加到列表中: 首先检查size为null还是head为null;然后它将节点插入为头。 头部和尾部都将指向新添加的节点。 如果head不为空,则新节点将是新尾,并且新尾将指向头,因为它是一个循环链表。
a.countNodes()将计算列表中存在的节点数。
定义新节点电流,该电流将指向头节点。 遍历列表以计数节点,方法是使当前节点指向列表中的下一个节点,直到当前节点再次指向头部。

程序:

public class CountNodes {
    //Represents the node of list.
        public class Node{
        int data;
        Node next;
        public Node(int data) {
            this.data = data;
        }
    }
    public int count;
    //Declaring head and tail pointer as null.
        public Node head = null;
    public Node tail = null;
    //this function will add the new node at the end of the list.
        public void add(int data){
        //Create new node
            Node newNode = new Node(data);
        //Checks if the list is empty.
            if(head == null) {
            //if list is empty, both head and tail would point to new node.
                head = newNode;
            tail = newNode;
            newNode.next = head;
        }
        else {
            //tail will point to new node.
                tail.next = newNode;
            //New node will become new tail.
                tail = newNode;
            //Since, it is circular linked list tail will point to head.
                tail.next = head;
        }
    }
    //this function will count the nodes of circular linked list
        public void countNodes() {
        Node current = head;
        do{
            //Increment the count variable by 1 for each node
                count++;
            current = current.next;
        }
        while(current != head);
        System.out.println("Count of nodes present in circular linked list: "+count);
    }
    public static void main(String[] args) {
        CountNodes cl = new CountNodes();
        cl.add(1);
        cl.add(2);
        cl.add(4);
        cl.add(1);
        cl.add(2);
        cl.add(3);
        //Counts the number of nodes present in the list
            cl.countNodes();
    }
}
输出:
Nodes of generated doubly linked list:
4 2 5 1 6 3 7
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4