c++用递归反向输出单链表中的每个节点元素值。(提示:不带头结点)
时间: 2023-12-10 14:38:29 浏览: 30
可以使用递归的方式输出单链表的每个节点元素值,具体的实现如下:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void reversePrint(ListNode* head) {
if (head == NULL) {
return;
}
reversePrint(head->next);
cout << head->val << " ";
}
```
上述代码中,我们先判断当前节点是否为空,如果为空则直接返回;否则先递归输出当前节点后面的所有节点,再输出当前节点的值。
需要注意的是,这里并没有使用头结点,因此在递归过程中需要判断当前节点是否为空。另外输出的顺序是从后往前输出,符合题目要求。
相关问题
用递归反向输出单链表中的每个节点元素值。(提示:不带头结点)
谢谢您的提问!以下是递归反向输出单链表中的每个节点元素值的代码:
```c++
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
void reversePrint(ListNode* head) {
if (head == nullptr) {
return;
}
reversePrint(head->next);
std::cout << head->val << " ";
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
std::cout << "Reverse Print of the Linked List: ";
reversePrint(head);
std::cout << std::endl;
return 0;
}
```
程序输出的结果应该是:
```
Reverse Print of the Linked List: 5 4 3 2 1
```
希望能够帮助到您!
用递归正向输出单链表中的每个节点元素值。(提示:不带头结点)
可以使用递归函数来遍历单链表,每次递归输出当前节点的值,并递归调用函数输出下一个节点的值。
以下是一个示例代码:
```c++
void printList(ListNode* node) {
if (node == nullptr) {
return;
}
cout << node->val << " ";
printList(node->next);
}
```
其中,ListNode 是单链表节点的定义,val 表示节点的值,next 指向下一个节点的指针。
在主函数中,可以调用这个函数输出单链表的所有节点值:
```c++
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
printList(head); // 输出 1 2 3
```
这样,就可以用递归正向输出单链表中的每个节点元素值了。
相关推荐
![](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)