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

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

//This is the list.h file

#include<iostream>
#include<cctype>
#include<cstring>

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: "<<result<<endl;
    new_list.display();

    return 0;
}

下面就展示结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值