如何在单链表里复制不是数字'2',然后将复制好的内容存储到数组中

关于单链表的知识点,小编就不在这里介绍了,如果有不懂的地方,自己查资料吧!
原题目是:Copy the contents of a linear linked list Except do not copy any 2’s and place the data into an array. Return the number of items copied

感觉这次目前小编用递归的方式来解决这道题,方法不是很好,太不简洁。若小编想到简洁的方法,还是用递归方式,就会更新这种方法。(别嘲笑小编!)

下面是list.h file 展示:

//This is the list.h file

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

using namespace std;

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

class list
{
    public:
        list(); //Supplied
        ~list(); //Supplied
        void build(); //Supplied
        void display(); //Supplied

        //Copy the contents of a linear linked list Except do not copy any 2's and place the data into an array
        //Return the number of items copied
        int copy_special();
    private:
        //Copy the contents of a linear linked list Except do not copy any 2's and place the data into an array
        //Return the number of itmes copied
        int copy_special(int *& array, node * head, int index, int count);
        int copy_special(node * head);

        node * head;
        node * tail;
};

因为题目要求是要将特殊的节点的内容输入到数组中,所以在argument list就得传进来数组。

下面是展示如何实现这三个函数的:

//This is the list.cpp file

#include "list.h"

int list::copy_special()
{
    int count = copy_special(head);
    int * array = new int[count];
    int result = copy_special(array,head,0,count);
    for(int I = 0; I < count; ++I)
    {
        cout<<array[I]<<" ";
    }
    cout<<endl;
    return result;
}

int list::copy_special(int *& array, node * head, int index, int count)
{
    if(!head)
        return 0;
    if(head->data != 2)
    {
        if(index < count)
        {
            array[index] = head->data;
        }
        return copy_special(array,head->next,index+1,count)+1;
    }
    return copy_special(array,head->next,index,count);
}

int list::copy_special(node * head)
{
    if(!head)
        return 0;
    if(head->data != 2)
    {
        return copy_special(head->next) + 1;
    }
    return copy_special(head->next);
}

至于如何在主函数里调用这些函数,小编就不在这里展示出来了

下面是展示结果:

小编想到更好的方法,第一时间会更新内容,敬请期待吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值