c++ - 放弃检查列表是否为空

标签 c++

由于您上次设法修复了我的代码,所以我想再次寻求您的帮助。

因为我已经有了一个包含五个元素的预定义列表,所以这段代码看起来很无意义,因为没有检查列表是否为空的目的。我似乎无法弄清楚谁可以绕过 if-else,只保留“插入”功能而不是检查列表是否为空...

#include <iostream>
#include <cmath>

using namespace std;

struct node
{
    string nameOfFood;
    int eatCalories;
    int number;
    node *next;

};

bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&last, string name, int eatCalories);
void insert(node *&head, node *&last, string name, int eatCalories);
void showList(node *current);


bool isEmpty(node *head)
{
    if(head == NULL)
        return true;
    else
        return false;
}

char menu()
{
    char choice;

    cout << "Menu\n";
    cout << "1. Add food, beverage etc.\n";
    cout << "2. Show the list of food(s), beverage(s) etc.\n";
    cout << "3. Update your current weight\n";
    cout << "4. What have you been eaten?\n";
    cout << "5. What exercise have you done?\n";
    cout << "6. Exit program \n";

    cin >> choice;

    return choice;

}

void insertAsFirstElement(node *&head, node *&last, string nameOfFood, int eatCalories)
{
    node *temp = new node;
    temp->nameOfFood = nameOfFood;
    temp->eatCalories = eatCalories;
    temp->next = NULL;
    head = temp;
    last = temp;
}

void insert(node *&head, node *&last, string nameOfFood, int eatCalories)
{
    if(isEmpty(head))
        insertAsFirstElement(head, last, nameOfFood, eatCalories);
    else
    {
        node *temp = new node;
        temp->nameOfFood = nameOfFood;
        temp->eatCalories = eatCalories;
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }

}

如果您需要更多代码,请告诉我?

希望得到您的帮助!

最佳答案

该检查是必要的,因为如果您的列表为空,那么您必须执行一定数量的操作,这些操作仅在这种情况下执行。

实现自己的链表真的没有任何意义。标准已经定义了比你的更灵活的类,参见 std::forward_list (单链表)和 std::list (双向链表) .

建议您在选择容器时默认使用std::vectorstd::array。在这种情况下,如果您只有 5 个元素的列表,只需使用 std::array 和自定义类型:

struct food
{
    string nameOfFood;
    int eatCalories;
    int number;
};

然后:

std::array<food, 5> food_list { ... };

关于c++ - 放弃检查列表是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28886782/

相关文章:

c++ - C++中可以不用纯虚函数实现抽象类吗?

c++ - Python C API 代码的 gcc 错误 - "ISO C++ forbids casting between pointer-to-function and pointer-to-object"

c++ - 间接多级智能指针

c++ - 将一个类放在单独的文件中不起作用[C++]

c++ - 如何以编程方式从头开始创建弯头连接器?

c++ - 我怎样才能让我的 va_list 参数自己重复?

c++ - Cocos2D-x; ui 未被识别为 namespace

c++ - 通过网络发送一个 bool 数组

c++ - 有数据的空闲缓冲区

python - 传递标准 :vector from C++ to Python via Ctypes: getting nonsensical values