您好,欢迎访问一九零五行业门户网

在C++中递归插入和遍历链表

我们得到了用于形成链表的整数值。任务是使用递归方法先插入然后遍历单链表。
在末尾递归添加节点如果 head 为 null → 将节点添加到 head
否则添加到 head( head → next )
递归遍历节点如果 head 为 null → 退出
否则打印( head → next )
示例输入− 1 - 2 - 7 - 9 - 10
输出
输出 strong>− 链表:1 → 2 → 7 → 9 → 10 → null
输入− 12 - 21 - 17 - 94 - 18
输出− 链表:12 → 21 → 17 → 94 → 18 → null
下面程序中使用的方法如下在这种方法中,我们将使用函数添加节点并遍历单链表并递归调用它们以进行下一个输入。
采用带有整数和下一个指针 sllnode* 的结构体 sllnode 。
函数 addtoend(sllnode* head, int data) 获取指向链表头的指针和数据部分的整数,并将节点添加到链表的末尾。
li>如果头指针为 null,则列表为空,现在添加一个新节点并将其设置为头。将 head → next 添加为 null。返回指向该节点的指针
如果 head 不为 null,则使用 head->next = addtoend(head->next, data) 将节点添加到 head → next。
函数 traverselist(sllnode* head) 从 head 开始遍历并打印每个值。
如果 head 为 null,则打印 null 并返回.
否则打印数据值并使用 traverselist(head->next) 遍历下一个。
在主创建列表中使用addtoend() 并使用 traverselist() 打印列表。
示例#include <bits/stdc++.h>using namespace std;struct sllnode { int data; sllnode* next;};sllnode* addtoend(sllnode* head, int data){ if (head == null){ sllnode *nodex = new sllnode; nodex->data = data; nodex->next = null; return nodex; } else{ head->next = addtoend(head->next, data); } return head;}void traverselist(sllnode* head){ if (head == null){ cout <<"null"; return; } cout << head->data << " -> "; traverselist(head->next);}int main(){ sllnode* head1 = null; head1 = addtoend(head1, 1); head1 = addtoend(head1, 8); head1 = addtoend(head1, 56); head1 = addtoend(head1, 12); head1 = addtoend(head1, 34); cout<<"linked list is :"<<endl; traverselist(head1); return 0;}
输出如果我们运行上述代码,将会生成以下输出
linked list is :1 -> 8 -> 56 -> 12 -> 34 -> null
以上就是在c++中递归插入和遍历链表的详细内容。
其它类似信息

推荐信息