给出计算一个单项链表所有节点数量的递归算法
时间: 2023-05-29 08:07:31 浏览: 185
以下是计算单项链表所有节点数量的递归算法,假设链表中每个节点都有一个指向下一个节点的指针:
```
int countNodes(Node* head) {
if (head == NULL) { // 如果链表为空,则节点数量为0
return 0;
}
else {
return 1 + countNodes(head->next); // 递归调用,每次加1
}
}
```
该算法的基本思路是,如果链表为空,则节点数量为0,否则将节点数量加1并递归调用函数来计算下一个节点的数量。最终,当遍历完整个链表时,返回节点数量的总和。
相关问题
用python给出计算一个单项链表所有节点数量的递归算法
以下为Python代码实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def countNodes(head: ListNode) -> int:
if head is None: # 链表为空,节点数量为0
return 0
else:
return 1 + countNodes(head.next)
# 测试
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
print(countNodes(n1)) # 输出3
```
首先定义了一个`ListNode`类来表示单项链表的节点,其中`val`表示节点的值,`next`表示指向下一个节点的指针。
然后定义了递归函数`countNodes`,它的参数是链表的头节点`head`,返回值是链表中节点的数量。如果链表为空,节点数量为0;否则,节点数量等于头节点之后节点的数量加1。
最后,我们创建了一个简单的单项链表并进行了测试。链表中有3个节点,因此输出为3。
用C语言写出单向链表查找节点的算法
以下是用 C 语言实现单向链表查找节点的算法示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 查找链表中第一个值为 val 的节点,返回该节点的指针,如果不存在则返回 NULL
struct ListNode* findNode(struct ListNode* head, int val) {
// 遍历链表
while (head != NULL) {
// 如果当前节点的值为 val,则返回该节点的指针
if (head->val == val) {
return head;
}
// 否则,继续遍历下一个节点
head = head->next;
}
// 链表中不存在值为 val 的节点,返回 NULL
return NULL;
}
int main() {
// 创建链表的头结点
struct ListNode* head = (struct ListNode*) malloc(sizeof(struct ListNode));
head->val = 1;
head->next = NULL;
// 添加新节点
struct ListNode* node1 = (struct ListNode*) malloc(sizeof(struct ListNode));
node1->val = 2;
node1->next = NULL;
head->next = node1;
// 添加新节点
struct ListNode* node2 = (struct ListNode*) malloc(sizeof(struct ListNode));
node2->val = 3;
node2->next = NULL;
node1->next = node2;
// 查找链表中值为 2 的节点
struct ListNode* node = findNode(head, 2);
if (node != NULL) {
printf("找到了节点,节点的值为 %d\n", node->val);
} else {
printf("未找到节点\n");
}
// 释放链表节点的内存
free(node1);
free(node2);
free(head);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)