Java链表递归部门人数

链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。在Java中,我们可以使用类来表示链表节点,并通过递归的方式来统计链表中的部门人数。

链表节点类

首先,我们定义一个链表节点类,包含部门名称和人数两个属性,以及指向下一个节点的指针。

public class DepartmentNode {
    String name;
    int count;
    DepartmentNode next;

    public DepartmentNode(String name, int count) {
        this.name = name;
        this.count = count;
        this.next = null;
    }
}

统计部门人数

接下来,我们定义一个递归方法来统计部门人数。该方法接收一个部门节点作为参数,并递归计算该节点以及其后续节点的人数总和。

public int countEmployees(DepartmentNode node) {
    if (node == null) {
        return 0;
    }
    
    return node.count + countEmployees(node.next);
}

示例

现在,我们创建一个简单的部门链表,并统计其中的人数。

public static void main(String[] args) {
    DepartmentNode node1 = new DepartmentNode("HR", 10);
    DepartmentNode node2 = new DepartmentNode("IT", 20);
    DepartmentNode node3 = new DepartmentNode("Finance", 15);

    node1.next = node2;
    node2.next = node3;

    int totalEmployees = countEmployees(node1);
    System.out.println("Total number of employees: " + totalEmployees);
}

部门人数关系图

下面是一个部门人数关系图,其中每个节点代表一个部门,包含部门名称和人数。

erDiagram
    Department ||--o{ Employee : has
    Department {
        string name
    }
    Employee {
        int count
    }

结论

通过递归的方式,我们可以方便地统计链表中部门的人数。在实际应用中,我们可以根据需要扩展链表节点类,添加更多属性,以满足具体的业务需求。同时,递归方法也可以应用于其他场景,如遍历链表、搜索特定节点等操作。希望本文能够帮助读者更好地理解Java链表的递归操作。