Python程序创建N个节点的循环链表并计算节点的数量

Python程序创建N个节点的循环链表并计算节点的数量

在Python中,我们可以使用class来定义一个节点,使用这些节点创建循环链表,并且统计循环链表中节点的数量。

更多Python相关文章,请阅读:Python 教程

Node类的定义

Node类包括两个数据成员,一个是存储节点值的data,另一个是指向下一个节点的指针next。

class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

创建循环链表

我们通过一个函数create_circular_linked_list来创建循环链表,参数N表示链表中节点的数量,返回值为头节点。

def create_circular_linked_list(N):
    if N <= 0:
        return None  # 如果节点数量为0,则返回None

    head = Node(1)  # 创建头节点
    cur_node = head  # 当前节点指向头节点

    for i in range(2, N+1):
        new_node = Node(i)  # 创建新节点
        cur_node.next = new_node  # 当前节点指向新节点
        cur_node = new_node  # 当前节点变为新节点

    cur_node.next = head  # 最后一个节点指向头节点,形成循环链表

    return head

我们可以调用create_circular_linked_list函数来创建一个包含10个节点的循环链表。

head = create_circular_linked_list(10)

计算节点数量

我们可以通过遍历循环链表来统计节点数量,代码如下:

def count_nodes(head):
    count = 0
    cur_node = head
    while cur_node:
        count += 1
        cur_node = cur_node.next
        if cur_node == head:  # 如果当前节点指向头节点,则遍历结束
            break
    return count

我们可以调用count_nodes函数来计算循环链表中节点的数量。

node_count = count_nodes(head)
print(f"节点数量:{node_count}")

示例代码

class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

def create_circular_linked_list(N):
    if N <= 0:
        return None  # 如果节点数量为0,则返回None

    head = Node(1)  # 创建头节点
    cur_node = head  # 当前节点指向头节点

    for i in range(2, N+1):
        new_node = Node(i)  # 创建新节点
        cur_node.next = new_node  # 当前节点指向新节点
        cur_node = new_node  # 当前节点变为新节点

    cur_node.next = head  # 最后一个节点指向头节点,形成循环链表

    return head

def count_nodes(head):
    count = 0
    cur_node = head
    while cur_node:
        count += 1
        cur_node = cur_node.next
        if cur_node == head:  # 如果当前节点指向头节点,则遍历结束
            break
    return count

head = create_circular_linked_list(10)
node_count = count_nodes(head)

print(f"节点数量:{node_count}")

输出结果为:

节点数量:10

结论

通过定义Node类,创建循环链表,以及遍历循环链表的代码,我们可以很容易地得到循环链表中节点的数量。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程