温馨提示×

c语言怎么求单链表的表长

小亿
112
2023-12-01 00:29:09
栏目: 编程语言

要求单链表的表长,只需要遍历整个链表,统计节点的个数即可。

例如,假设链表的定义如下:

typedef struct Node{
    int data;  // 存储数据
    struct Node *next; // 指向下一个节点的指针
}Node;

// 定义链表头节点
Node *head = NULL;

下面给出求单链表表长的函数实现:

int getLength(){
    int length = 0;
    Node *current = head;  // 从头节点开始遍历
    while(current != NULL){
        length++;
        current = current->next;
    }
    return length;
}

在主函数中调用该函数即可得到单链表的表长。

0