求单链表长度代码C语言
时间: 2023-08-18 13:15:43 浏览: 47
下面是一个单链表长度的C语言示例代码:
```c
/* 单链表节点结构体定义 */
struct ListNode {
int val;
struct ListNode *next;
};
int getLinkedListLength(struct ListNode* head) {
int count = 0;
struct ListNode* curr = head;
while (curr != NULL) {
count++;
curr = curr->next;
}
return count;
}
```
该函数接收单链表的头节点 `head`,并返回链表的长度。函数内部通过遍历链表,使用一个计数器变量 `count` 统计链表中节点的个数,最后返回计数器的值即可。
相关问题
查找单链表元素的C语言代码
以下是查找单链表元素的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义单链表的节点结构体 */
struct ListNode {
int val;
struct ListNode *next;
};
/* 创建单链表 */
struct ListNode *createList(int *arr, int n) {
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
for (int i = 0; i < n; i++) {
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = arr[i];
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
/* 查找单链表中是否存在指定元素 */
int searchList(struct ListNode *head, int target) {
while (head != NULL) {
if (head->val == target) {
return 1;
}
head = head->next;
}
return 0;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
struct ListNode *head = createList(arr, n);
int target = 3;
int found = searchList(head, target);
printf("%d\n", found);
return 0;
}
```
该代码中,首先定义了单链表的节点结构体`struct ListNode`,包括一个`val`表示节点值和一个`next`指针表示下一个节点的地址。接着,创建了一个`createList`函数,用于创建单链表。该函数接受一个整型数组和数组长度,依次将数组中的元素加入到单链表中。最后,定义了一个`searchList`函数,用于查找单链表中是否存在指定元素。在函数中,使用`while`循环遍历单链表,若找到目标元素则返回1,否则返回0。在`main`函数中,首先创建一个整型数组并通过`createList`函数创建单链表,然后将目标元素设为3,并将`head`和`target`传入`searchList`函数中。最后,输出查找结果。
c语言数据结构单链表长度
C语言数据结构单链表长度可以通过遍历单链表来计算。具体实现方法如下:
1. 定义一个变量count,用于记录单链表长度,初始值为0。
2. 从单链表的头节点开始,依次遍历单链表的每个节点,每遍历一个节点,count的值加1。
3. 遍历结束后,count的值即为单链表长度。
以下是C语言代码实现:
```
typedef struct Node {
int data;
struct Node* next;
} Node;
int getLinkedListLength(Node* head) {
int count = 0;
Node* p = head;
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
```
其中,Node是单链表节点的结构体,包含数据域data和指向下一个节点的指针next。getLinkedListLength函数的参数是单链表的头节点指针,返回值是单链表的长度。函数通过遍历单链表,计算节点数量来实现求单链表长度的功能。