递归复制链接列表

时间:2017-11-03 07:30:27

标签: c++ recursion linked-list

在谷歌搜索了一段时间后,我得出的结论是我很难过。

问题:

递归复制链表(以及反向复制,但我稍后会越过那个桥。)

我有以下代码:

// In list.h
struct node {
    int data;
    node * next;
}

// In list.cpp
// Recursive copy wrapper
int list::copy() {                              
    if(!head) {                                 
        return 0;                               
    }                                           
    node *new_node = NULL;
    return copy(new_node, head);                                          
}                                               

// Recursive copy function
int list::copy(node *& dest, node * src) {      
    if(!src) {                                  
        dest = NULL;                            
        return 0;                               
    }                                           

    dest = new node();                          
    dest->data = src->data;
    // *dest->next = src->next;* // Not sure what to do here?

    return copy(dest->next, src->next) + 1; // count number of nodes copied  
}

注意:这不是家庭作业,而是预备技术面试考试的问题。

在这一点上,我相当肯定我自己无法做到这一点,所以任何帮助都会受到赞赏。提前谢谢!

2 个答案:

答案 0 :(得分:1)

根据我的理解,列表需要先递归复制,新头的引用需要指向副本的头部;这可以通过以下方式完成。

int list::copy(node *& dest, node * src)
{      
    if(!src)
    {                                  
        dest = NULL;                            
        return 0;                               
    }                                           

    dest = new node();                          
    dest->data = src->data;

    node* TailCopy = null; // reference to copy of remaining list

    int TotalNumOfNodes = 1 + copy(Tail, src->next) + 1;

    dest->next = TailCopy; // let copy of head refer to copy of tail

    return TotalNumOfNodes;
}

答案 1 :(得分:0)

好吧,int list::copy(node *& dest, node * src)完全正确,并成功将列表尾部复制到另一个列表尾部。问题在于int list()一个毫无意义的问题:你成功地将当前列表中的所有节点复制到一个新的链中,并在完成时无可挽回地泄漏所有内存!

如果你想构建一些有意义的东西,你可以在复制构造函数中使用递归副本:

list(const list& other) {
    copy(head, other.head);
}

这不使用copy(可能是静态)方法的返回值,我可以确认它是预期值。

相关问题