首页 > 解决方案 > 在列表中插入值

问题描述

我想不通....我的代码没有打印任何东西。我需要创建一个不同的节点还是我编写了错误的代码?请帮忙。一个解释将不胜感激。代码只能去它说“从这里开始//从这里结束。不能修改之外的任何内容。

#include <iostream>

using namespace std;

class node
{
    int value;
    node* next;

public:
    node(int value, node* next)
    {
        this->value = value;
        this->next = next;
    }

    void print()
    {
        node* current = this;

        while (current != nullptr) {
            cout << current->value << " ";
            current = current->next;
        }
    }

    //Add the value end at the end of the list (i.e. after the last element)
    void add(int n)
    {
        **// Your code starts here**
        node* curr = this;
        curr->value = n;
        if (curr->next == NULL)
        {
            curr->add(n);
        }
        curr->next = NULL;
        **// Your code ends here**    
    }

    //Return the sum of all the elements in the list
    int sum()
    {
        **// Your code starts here**
        int sum = 0;
        node* curr = this;
        while (curr != NULL)
        {
            sum += curr->value;
            curr = curr->next;
        }
        return sum;
        **// Your code ends here**    
    }

    //Multiplies each element in the list by n
    void mult(int n)
    {
        **// Your code starts here**
        node* curr = this;
        
        while (curr != NULL)
        {
            curr->value = curr->value * n;
            curr = curr->next;
        }
        **// Your code ends here**
    }

    //Find the maximum value in the list
    int max()
    {
        **// Your code starts here**
        node* curr = NULL;
        int max_value = curr->value;

        while (curr != NULL)
        {
            if (curr->value > max_value)
                max_value = curr->value;
            curr = curr->next;
        }
        return max_value;
        **// Your code ends here**    
    }
};

//After
int main()
{
    node* n = NULL;
    cout << "//Inserting values at the end" << endl;
    n->add(10);
    n->add(20);
    n->add(30);
    cout << endl << "10 20 30" << endl;
    cout << "//printing the values" << endl;
    n->print();
    cout << endl << "//finding sum for the values in the list" << endl;
    cout << n->sum();
    cout << endl << "//calling multiply funciton with 4 as n" << endl;
    n->mult(4);
    n->print();
    cout << endl << "//finding the max value in the list" << endl;
    cout << n->max();
}

预期值: 原始:1 2 3 4 5 6 7 8 9 10 11 总和:66 乘以 4:4 8 12 16 20 24 28 32 36 40 44 最大值:44

标签: c++

解决方案


推荐阅读