求带头结点的单链表中的结点个数
时间: 2023-06-19 13:05:41 浏览: 62
带头结点的单链表中的结点个数,可以通过遍历整个链表来统计。具体的实现如下:
1. 定义一个计数器count,初始值为0。
2. 从头结点的下一个节点开始遍历链表,每遇到一个节点,就将计数器count加1。
3. 遍历完整个链表后,count的值即为链表中的结点个数。
以下是一个示例代码:
```c++
int countNode(ListNode* head) {
int count = 0;
ListNode* p = head->next;
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
```
其中,ListNode为单链表的结点类型,head为带头结点的单链表的头指针。
相关问题
c语言设计一个算法,求一个带头结点单链表中的结点个数。
以下是C语言实现带头结点单链表结点个数的算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct node {
int data;
struct node *next;
} Node, *LinkList;
// 初始化带头结点单链表
LinkList InitList() {
LinkList head = (LinkList) malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 在单链表尾部插入结点
void InsertTail(LinkList head, int data) {
Node *p = head;
while (p->next != NULL) {
p = p->next;
}
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
p->next = newNode;
}
// 计算单链表结点个数
int GetNodeCount(LinkList head) {
int count = 0;
Node *p = head->next;
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
int main() {
// 初始化单链表
LinkList head = InitList();
// 在单链表尾部插入结点
InsertTail(head, 1);
InsertTail(head, 2);
InsertTail(head, 3);
InsertTail(head, 4);
InsertTail(head, 5);
// 计算单链表结点个数
int count = GetNodeCount(head);
printf("The number of nodes in the list is: %d", count);
return 0;
}
```
输出结果为:
```
The number of nodes in the list is: 5
```
求不带头结点的单链表结点个数
不带头结点的单链表结点个数可以通过遍历链表并计数的方式来求解。以下是一个示例代码:
```c
int Length_Linklist(Linklist *L) {
int count = 0;
LNode *p = *L;
while(p) {
count++;
p = p->next;
}
return count;
}
```
该函数首先将计数器count初始化为0,并将指针p指向链表的第一个节点。然后,通过循环遍历链表,每遍历一个节点,计数器count加1,并将指针p指向下一个节点,直到遍历完整个链表。最后,返回计数器count的值,即为链表的结点个数。