Class practice 4
This practice problem will require you to implement a simple list, supporting some common functions.
The expected header is as follows (p025.h):
#ifndef _P025
#define _P025
class MyList {
int value;
MyList* next;
MyList* last;
public:
int length;
MyList();
~MyList();
void prepend(int val);
void append(int val);
int get(int ind);
int give(int ind, int val);
};
#endif
Class Specification
MyList::MyList
Constructor. This should initialise the value of value to -1, and next and last to NULL (or 0x0).
void MyList::prepend(int val);
Insert val to the beginning of the list.
void append(int val);
Insert val to the end of the list.
int get(int ind);
Return the value at index ind. If ind is out of bound, you should return -1.
int give(int ind, int val);
Change the value at index ind to val, and return val.
If ind is out of bound, you should return -1.
Testing
Main programme (main.cpp):
#include <iostream>
#include "p025.h"
using namespace std;
int main() {
int n, k, val;
cin >> n;
MyList list;
for (int i=0;i<n;i++) {
cin >> k >> val;
if (k==0){
list.prepend(val);
} else if (k==1) {
list.append(val);
} else if (k==2) {
cout << list.get(val) << endl;
} else {
int op;
cin >> op;
cout << list.give(val, op) << endl;
}
}
return 0;
}
You can use this programme to run some tests.
The main programme is expecting a single number n on the first line.
The following n lines each contain integers k, val, and optionally op, calling the class to perform specific actions.
Sample Input
5
0 1
0 2
2 -1
2 0
2 1
Sample Output
-1
2
1
Comments