2015-03-05 3 views
1

Как вам удалось исправить мой код в прошлый раз, я снова хотел попросить вашу помощь.Отмена проверки, если список пуст

Поскольку у меня уже есть предопределенный список из пяти элементов, этот код кажется довольно абсурдным, так как нет никакой цели проверить, пуст ли список. Я не могу показаться, чтобы выяснить, кто в обход если-то еще, а просто держать функцию «вставить» вместо того, чтобы также проверить, если список пуст ...

#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; 
    } 

} 

Позвольте мне знать, если вам нужно больше кода?

Надеюсь на вашу помощь!

ответ

2

Эта проверка необходима, поскольку, если ваш список пуст, вам необходимо выполнить определенное количество операций, которые выполняются только в этом случае.

В реализации собственного связанного списка действительно нет никакой цели. Классы, которые являются более гибкими, чем ваши, уже были определены стандартом, см. std::forward_list (отдельно связанный список) и std::list (двусвязный список).

При выборе контейнера рекомендуется по умолчанию использовать std::vector или std::array. В этом случае, если вы просто список из 5 элементов, просто использовать std::array и тип пользовательского:

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

, а затем:

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

Но мой список никогда не будет пустым, так как у меня есть пять предопределенных элементов. Я отправлю остальную часть кода, и, может быть, вы поймете, что я имею в виду? Или еще, это я неправильно понял.

#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; 
 
    } 
 
    
 
} 
 
void showList(node *current) 
 
{ 
 
    if(isEmpty(current)) 
 
     cout << "The list of foods is empty\n"; 
 
    else 
 
    { 
 
     cout << "The list of foods contain: \n"; 
 
     int number = 0; 
 
     
 
     while(current != NULL) 
 
     { 
 
      ++number; 
 
      cout << number << " " << current->nameOfFood << " " << current->eatCalories << " calories" << endl; 
 
      
 
      current = current->next; 
 
      
 
     } 
 
    } 
 
} 
 
node* subtractCalories(node *head) 
 
{ 
 
    int choice; 
 
    showList(head); 
 
    cout << "Pick the food, beverage etc. from the list by number\n"; 
 
    cin >> choice; 
 
    
 
    int number = 1; 
 
    node *current = head; 
 
    while (current != NULL && choice != number) 
 
    { 
 
     ++number; 
 
     current = current->next; 
 
    } 
 
    cout << "You have choosen: " << current->nameOfFood << endl; 
 
    return current; 
 
} 
 

 

 
int main(int argc, const char * argv[]) { 
 
    
 
    double caloriesToBurn; 
 
    double weight; 
 
    double height; 
 
    double BMI; 
 
    
 
    int answerWhile = 1; 
 
    int answerToExercise = 0; 
 
    float minutesExerciseInHour; 
 
    float caloriesBurned; 
 
    
 
    node *head = NULL; 
 
    node *last = NULL; 
 
    node *current; 
 
    char choice; 
 
    int eatCalories; 
 
    string nameOfFood; 
 
    
 
    insert(head, last, "Tuna (in oil)", 190); 
 
    insert(head, last, "Milkchocolate (Marabou)", 540); 
 
    insert(head, last, "Milk (skimmed)", 33); 
 
    insert(head, last, "Ice Tea (white peach)", 1); 
 
    insert(head, last, "Peanuts (roasted and salted)", 624); 
 
    
 
    cout << "*** Welcome to the calorie calculator! ***\n"; 
 
    cout << "To get started, i need some numbers from you\n"; 
 
    cout << "Please enter the number of calories you need to burn today:\n"; 
 
    cin >> caloriesToBurn; 
 
    cout << "What are your current weight? (please enter in kilograms)\n"; 
 
    cin >> weight; 
 
    cout << "And lastly i need to know your height (please enter in centimeters)\n"; 
 
    cin >> height; 
 
    BMI = (weight/pow(height/100,2)); 
 
    cout << "Your BMI is: " << BMI << endl; 
 
    
 
    if (BMI <= 18.5) 
 
     cout << "You are in the range: under weight" << endl; 
 
    else if ((BMI > 18.5) && (BMI < 25)) 
 
     cout << "You are in the range: normal weight" << endl; 
 
    else 
 
     cout << "You are in the range: over weight" << endl; 
 
    do{ 
 
     
 
     choice = menu(); 
 
     switch(choice) 
 
     { 
 
      case '1': 
 
       cout << "Enter the name of the food, beverage etc.:"; 
 
       cin >> nameOfFood; 
 
       cout << "How many calories did it contain? (measured per 100 grams):"; 
 
       cin >> eatCalories; 
 
       
 
       insert(head, last, nameOfFood, eatCalories); 
 
       break; 
 
       
 
      case '2': showList(head); 
 
       break; 
 
       
 
      case '3': cout << "What you wanna update your weight to?\n"; 
 
       cin >> weight; 
 
       cout << "Your weight have been update to: \n"; 
 
       cout << weight << endl; 
 
       if (BMI <= 18.5) 
 
        cout << "You are in the range: under weight" << endl; 
 
       else if ((BMI > 18.5) && (BMI < 25)) 
 
        cout << "You are in the range: normal weight" << endl; 
 
       else 
 
        cout << "You are in the range: over weight" << endl; 
 
       
 
       break; 
 
       
 
      case '4': 
 
       cout << endl << "You need to consume " << caloriesToBurn << " calories today!" << endl << endl; 
 
       current = subtractCalories(head); 
 
       caloriesToBurn = caloriesToBurn-current->eatCalories; 
 
       cout << endl << "You need to eat " << caloriesToBurn << " calories more today!" << endl; 
 
       break; 
 
       
 
      case '5': 
 
       
 
       do 
 
       { 
 
        cout << "How many minuttes have you ben exercising (please enter in hours)\n"; 
 
        cin >> minutesExerciseInHour; 
 
        cout << "What type of exercise have you been doing?" <<endl; 
 
        cout << "1. Running" <<endl; 
 
        cout << "2. Swimming" <<endl; 
 
        cout << "3. Cycling" <<endl; 
 
        cin >> answerToExercise; 
 
        
 
        switch(answerToExercise) 
 
        { 
 
         case 1: 
 
          caloriesBurned = weight*7.5*minutesExerciseInHour; 
 
          cout << "You have burned: " << caloriesBurned << "calories\n"; 
 
          caloriesToBurn = caloriesToBurn + caloriesBurned; 
 
          cout << "You have: " << caloriesToBurn << " left today\n"; 
 
          break; 
 
          
 
         case 2: 
 
          caloriesBurned = weight*7*minutesExerciseInHour; 
 
          cout << "You have burned: " << caloriesBurned << "calories\n"; 
 
          caloriesToBurn = caloriesToBurn + caloriesBurned; 
 
          cout << "You have: " << caloriesToBurn << " left today\n"; 
 
          break; 
 
          
 
         case 3: 
 
          caloriesBurned = weight*6*minutesExerciseInHour; 
 
          cout << "You have burned: " << caloriesBurned << "calories\n"; 
 
          caloriesToBurn = caloriesToBurn + caloriesBurned; 
 
          cout << "You have: " << caloriesToBurn << " left today\n"; 
 
          break; 
 
          
 
         default: cout << "I think something went wrong? Try again.."; 
 
        } 
 
       } 
 
       
 
       while (answerWhile != 1); 
 
       
 
      default: cout << "System exit\n"; 
 
     } 
 
    }while(choice != '6'); 
 
    
 
    
 
    return 0; 
 
}

+0

Почему вы используете '' и теги для создания кода HTML? – Shoe

0

Я думаю, я понимаю, с проверкой на пустой список - поэтому я возьму свой код на другой вопрос.

У меня есть функция InsertAsFirstElement, но на данный момент я думаю, что я забыл, что делает функция, потому что нигде в коде не будет «вставить первым элементом», так может кто-то сказать, что делает эта функция?

Извините за неудобства!

+0

Эмиль, вы можете добавить комментарии (найдите ссылку «добавить комментарий» внизу каждого ответа). Вы должны добавить ответ только тогда, когда хотите дать ответ, который решает вопрос (а не только ответ на существующий ответ). – nacho4d

+0

Спасибо. Не знал разницы между ответом и комментарием :) –

Смежные вопросы