#include <iostream> #define ERROR 0 #define OK 1 using namespace std;
template <typename Type> class Point { public: Type data; Point<Type> *next; Point() { this -> next = NULL; } Point(Type data) { this -> data = data; this -> next = NULL; } };
template <typename Type> class Train { private: Point<Type> *head; int len; public: Train() { head = NULL; len = 0; } ~Train() { Point<Type> *p = this -> head; while(p != NULL) { Point<Type> *old = p; p = p -> next; free(old); } } void set(int len) { this -> len = len; } int get() { return this -> len; } bool insert(Point<Type> *t, int inx) { if (inx < 0 || inx > this -> len) { return ERROR; } if (this -> head == NULL) { this -> len ++; this -> head = t; return OK; } if (inx == 0) { t -> next = this -> head; this -> head = t; this -> len ++; return OK; } Point<Type> *p = this -> head; int tot = 0; while(tot < inx - 1) { p = p -> next; tot++; } t -> next = p -> next; p -> next = t; this -> len ++; return OK; } int query(Type val) { if (this -> head == NULL) { return -1; } Point<Type> *p = this -> head; int tot = 0; while(p != NULL) { if (p -> data == val) { return tot; } p = p -> next; tot++; } return -1; } void output() { if (this -> head == NULL) { return; } Point<Type> *p = this -> head; int tot = 0; while(p != NULL) { cout << tot++ << ":" << p -> data << " "; p = p -> next; } cout << endl; } bool del(int inx) { if (inx < 0 || inx >= this -> len) { return ERROR; } Point<Type> *p = this -> head; int tot = 0; if (inx == 0) { this -> head = this -> head -> next; free(p); this -> len --; return OK; } while(tot < inx - 1) { p = p -> next; tot++; } Point<Type> *del = p -> next; p -> next = del -> next; free(del); this -> len --; return OK; } void reverse() { if (this -> head == NULL) { return; } Point<Type> *p = head -> next; head -> next = NULL; while(p != NULL) { Point<Type> *p2 = p -> next; p -> next = head; head = p; p = p2; } } };
int main(int argc, char const *argv[]) { Train<int> trian; int m, a, b, t; cin >> m; for (int i = 0; i < m; i++) { cin >> t; switch (t) { case 1: { cin >> a >> b; Point <int> *p = (Point <int> *)malloc(sizeof(Point <int>)); p -> data = b; p -> next = NULL; if(trian.insert(p, a)) { cout << "success" << endl; } else { cout << "failed" << endl; } break; } case 2: { trian.output(); break; } case 3:{ cin >> a; if (trian.del(a)) { cout << "success" << endl; } else { cout << "failed" << endl; } break; } case 4:{ cin >> a; int inx = trian.query(a); if (inx != -1) { cout << inx << endl; } else { cout << "failed" << endl; } break; } default: trian.reverse(); } } return 0; }
近期评论