445 views
3 votes
Fill in the missing functions/classes to enable the program to compile and work correctly. This program simulates a train, where you start with just an engine. You have three options: go to the next train (forward towards the engine), go to the previous train (away from the engine) or add a train behind the current train car. You may not change main(), we will check to ensure it is exactly the same. You should be able to train cars anywhere, and this will insert it into that part of the train. For this part, you do not need to worry about deleting dynamic memory.

1 Answer

4 votes

Answer:

See Explaination

Step-by-step explanation:

#include <iostream>

#include <string>

using namespace std;

class train{

private:

string data;

train *next;

train *prev;

public:

train(string name){

data = name;

next = NULL;

prev = NULL;

}

bool hasNext(){

return next != NULL;

}

bool hasPrevious(){

return prev != NULL;

}

train *nextTrain(){

return next;

}

train *previousTrain(){

return prev;

}

string getName(){

return data;

}

void add(string name){

train *temp = new train(name);

temp->prev = this->prev;

if(this->prev != NULL)

this->prev->next = temp;

temp->next = this;

this->prev = temp;

}

void remove(){

if(prev != NULL){

if(prev->prev != NULL){

prev->prev->next = this;

this->prev = prev->prev;

}

this->prev = NULL;

}

}

};

int main()

{

train engine = train("Engine");

train* current = &engine;

string choice;

do

{

if(current -> hasNext())

{

cout << "Next train: " << current -> nextTrain() -> getName() << endl;

}

cout << "Current train: " << current -> getName() << endl;

if(current -> hasPrevious())

{

cout << "Previous train: " << current -> previousTrain() -> getName() << endl;

}

cout << "Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, (r) to remove a train or (q)uit?\\";

getline(cin,choice);

if(tolower(choice[0]) == 'n' && current -> hasNext())

{

current = current -> nextTrain();

}

else if(tolower(choice[0]) == 'p' && current -> hasPrevious())

{

current = current -> previousTrain();

}

else if(tolower(choice[0]) == 'a')

{

cout << "Which train is this?\\";

string name;

getline(cin, name);

current->add(name);

}

else if(tolower(choice[0]) == 'r')

{

current->remove();

}

}while(tolower(choice[0]) != 'q');

}

User Benny Schmidt
by
5.9k points