c语言中,求单链表的表长
时间: 2024-10-20 21:14:22 浏览: 51
在 C 语言中,求单链表的长度(即表长)通常需要遍历整个链表并计数节点。以下是一个简单的算法步骤:
1. 初始化一个变量 `length` 或 `count` 为0,用于存储链表长度。
2. 创建一个指针 `current` 并将其指向链表的头节点。
3. 使用一个 while 循环,当 `current` 指针不为空(`current != NULL`)时,执行以下操作:
a. 将 `length` 加一。
b. 将 `current` 向后移动一位,指向下一个节点 (`current = current->next;`)。
4. 循环结束后,`length` 的值就是链表的实际长度。
以下是相关的 C 代码示例:
```c
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
int getLinkedListLength(struct Node* head) {
if (head == NULL) {
return 0;
}
int length = 0;
struct Node* current = head;
while (current != NULL) {
length++;
current = current->next;
}
return length;
}
// 示例链表创建函数
struct Node* createList(int arr[], int n) {
// ... 实现链表创建代码 ...
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
struct Node* head = createList(arr, n);
int listLength = getLinkedListLength(head);
printf("链表的长度是: %d\n", listLength);
return 0;
}
```
阅读全文
相关推荐
















