COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
train.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <cstdlib>
3#include <string>
4using namespace std;
5
6
7struct Car {
8 string id;
10};
11
12void appendCar(Car *&head, string id);
13void printTrain(Car *&head);
14
15int main() {
16 Car *head = NULL;
17 int n;
18 cin >> n;
19 string id;
20 for (int i = 0; i < n; i++) {
21 cin >> id;
22 appendCar(head, id);
23 }
24 printTrain(head);
25
26 return 0;
27}
28
29// Please implement the function appendCar() here.
30void appendCar(Car *&head, string id) {
31 if (head == NULL) {
32 head = new Car;
33 head->id = id;
34 head->next = NULL;
35 } else {
36 Car *current = head;
37 while (current->next != NULL) {
38 current = current->next;
39 }
40 current->next = new Car;
41 current->next->id = id;
42 current->next->next = NULL;
43 }
44}
45
46void printTrain(Car *&head) {
47 Car *current = head; (*current).next
48 while (current != NULL) {
49 if (current->next != NULL) {
50 cout << current->id << ", ";
51 }
52 else {
53 cout << current->id;
54 }
55 current = current->next;
56 }
57}
58
Definition train.cpp:7
Car * next
Definition train.cpp:9
string id
Definition train.cpp:8
void appendCar(Car *&head, string id)
Definition train.cpp:30
void printTrain(Car *&head)
Definition train.cpp:46
int main()
Definition train.cpp:15