ABD*_*ABD 1 c++ debugging memory-management linked-list
在下面的代码中,我尝试创建一个字符串链接列表.然后我使用链表来存储由函数(名为myFunction)生成的输出,该函数以递归方式调用自身.在测试/调试代码时,我注意到如果我在执行函数后打印链表的内容(应该将项添加到链表中),则不打印任何内容.但是,如果我在从函数内部添加项目后尝试打印链接列表,它可以正常工作.
在调用myFunction后,似乎删除了整个链表.另一方面,当我向链表添加元素时,我正在使用动态内存分配,所以我没有看到问题.
请帮忙!
#include <cstdlib>
#include <iostream>
template <class T>
class node{
public:
node *next;
T data;
node(){next=0;};
void print();
};
template <class T>
void node<T>::print(){
std::cout << data;
}
template <class T>
class List{
public:
node<T> *head;
List(){head=0;};
void add(T data);
void print();
int len();
};
template <class T>
int List<T>::len(){
int i=0;
node<T> *current=head;
while(current!= 0){
i++;
current=current->next;
}
return i;
};
template <class T>
void List<T>::add(T myData){
node<T> *current=head;
if(head==0){
head= new node<T>;
head->data=myData;
}
else{
while(current->next!=0){
current=current->next;
}
current->next = new node<T>;
current->next->data=myData;
}
}
template <class T>
void List<T>::print(void){
node<T> *current=head;
if(head==0){
return;
}
else{
do{
std::cout << current->data << " ";
current=current->next;
}while(current!=0);
}
}
void myFunction(List<std::string> myList, int n, std::string starter, int leftParens, int rightParens){
int remainingLength = leftParens+rightParens;
if(remainingLength==0){
myList.add(starter);
std::cout <<myList.len() << std::endl;
}
if(leftParens >0){
myFunction(myList, n, starter+"(", leftParens-1, rightParens);
}
if(leftParens==0 and rightParens >0){
myFunction(myList, n, starter+")", leftParens, rightParens-1);
}
}
int main(int argc, char** argv) {
List<std::string> myList;
myFunction(myList, 5, "", 5, 5);
std::cout <<myList.len();
}
Run Code Online (Sandbox Code Playgroud)
您传递myList到myFunction由价值.到所做的任何更改myList的功能是改变副本,而不是原来myList的main.
更改myFunction以便通过引用接受其参数.然后,对其进行的任何更改myFunction也将在中显示main.
void myFunction(List<std::string>& myList, int n,
// ^^
std::string starter, int leftParens, int rightParens){
Run Code Online (Sandbox Code Playgroud)