复制单链表成为新的链表,然后return the number of items in the new list

关于单链表的知识点,小编就不在这里介绍了,那么就直接上代码吧!

//This is the list.h file

#include
#include
#include

using namespace std;

struct node
{
    int data;
    node * next;
};

class list
{
    public:
        //These functions already supplied
        list();  //Supplied
        ~list(); //Supplied
        void build(); //Supplied
        void display(); //Supplied

        //Copy the contents of a linear linked list and make a new linear linked list
        //Return the number of items in the new list
        int copy_list(list & to_copy);

    private:
        //Copy the contents of a linear linked list and make a new linked list
        //Return the number of items in the new list
        int copy_list(node *& new_head,node*& new_tail, node * head);

        node * head;
        node * tail;
};

因为建立链表需要用到tail指针,那么在函数的prototype里就得传入新的tail指针来指向新的链表

下面是如何实现这两个函数的代码展示:

//This is the list.cpp file
#include "file.h"

int list::copy_list(list & to_copy)
{
    return copy_list(to_copy.head,to_copy.tail,head);
}

int list::copy_list(node *& new_head, node *& new_tail, node * head)
{
    if(!head)
    {
        new_head = NULL;
        return 0;
    }
    new_head = new node;
    new_head->data = head->data;
    new_tail = new_head;
    return new_tail->data + copy_list(new_head->next,new_tail,head->next);
}

下面是展示如何在主函数里调用函数:

//This is the main.cpp

#include "list.h"

int main()
{
    //This is the original list object
    list object;
    object.build();  //Builds a LLL
    object.display(); //displays the LLL

    //This declares a new object
    list new_list;
    //Copy the contents of a linear linked list and make a new linear linked list
    //Return the number of items in the new list
    int result = object.copy_list(new_list);
    cout<<"The result is: "<return 0;
}

下面就展示结果:
复制单链表成为新的链表,然后return the number of items in the new list_第1张图片

你可能感兴趣的:(数据结构)