附加带有递归的链表 [英] Append linked list with recursion
问题描述
我想要一个插入函数,该函数调用私有递归插入函数,该函数将下一个数字添加到链接列表的末尾.我在应使用哪些参数以及在递归插入函数中应使用什么参数时遇到了麻烦.我认为递归插入功能需要Node指针来递归地进行操作.
I want an insert function that calls a private recursive insert function that adds the next number to the end of a linked list. I am having trouble on which parameters I should use and what should be in the recursive insert function. I am thinking that the recursive insert function needs a Node pointer to step through recursively.
class LinkedList{
private:
struct Node{
int data; //stores data in nodes
Node* next;
~Node(){delete next;}
};
public:
LinkedList(){ first = NULL;}
~LinkedList(){delete first;}
void print() const {
print( first );
}
void insert(const int d){ //here is where the first insert method is
insert(first, d);
}
private:
Node* first;
这是我所坚持的功能...
Here is the function that I am stuck on...
void insert(Node* p, const int d){ //this is the private recursive one
Node* temp = new Node;
temp->data=d;
if(p->next == NULL) p->next = temp;
else insert(p->next, d);
}
};
int main() {
int a[] = { 1, 2, 3, 4, 5, 6};
LinkedList list;
for(int i=0; i<6; i++)
list.insert( a[i] );
}
我想知道如何通过使参数不同来使insert函数过载.我还想知道我是否正确地执行了递归函数.
I want to know how to get the insert function to overload by getting the parameters different. I also want to know if I am stepping through the recursive function correctly.
推荐答案
调用递归函数的函数应类似于
The function that calls the recursive function should look like
void insert(const int d){
insert(first, d);
}
递归函数应该看起来像
void insert(Node*& p, const int d){
Node* temp = new Node;
temp->data=d;
if(p == NULL) p = temp;
else insert(p->next, d);
}
这篇关于附加带有递归的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!