Class practice 5


Submit solution

Points: 2
Time limit: 1.0s
Memory limit: 64M

Author:
Problem type
Allowed languages
C++, Python3

This practice problem will require you to implement a simple list, supporting some common functions.

In addition to your work on P025, P026 requires you to add support for del function to the list (removing an element from the list).

The expected header is as follows (p026.h):

#ifndef _P026
#define _P026
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);
    int del(int ind);
};
#endif

Class Specification

The only addition to P025 is the following member function:

int delete(int ind);

Delete element at index ind. Return 0 if successful, return -1 if out of bound.

Hint: be careful with the destructor.

Testing

Main programme (main.cpp):

#include <iostream>
#include "p026.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 if (k==3) {
            int op;
            cin >> op;
            cout << list.give(val, op) << endl;
        } else {
            cout << list.del(val) << 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

10
0 1
0 2
2 -1
2 0
2 1
0 1
0 2
0 3
4 1
4 2

Sample Output

-1
2
1
0
0

Comments

There are no comments at the moment.