1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| namespace LIST { struct NODE { int data; NODE *next; NODE() : next(nullptr) {} NODE(int d, NODE *n = nullptr) : data(d), next(n) {} ~NODE() {} };
NODE *head = nullptr; int len = 0;
void init() { len = 0; }
NODE *move(int i) { NODE *p = head; while (i-- > 0) p = p->next; return p; }
void insert(int i, int x) { if (i == 0) { NODE *p = move(len - 1); if (len == 0) { head = new NODE(x); head->next = head; } else head = p->next = new NODE(x, head); } else { NODE *p = move(i - 1); p->next = new NODE(x, p->next); } len++; }
void remove(int i) { if (i == 0) { NODE *p = move(len - 1), *q = p->next; head = p->next = q->next; delete q; } else { NODE *p = move(i - 1), *q = p->next; p->next = q->next; delete q; } len--; if (len == 0) head->next = nullptr; }
void remove_insert(int i) { int x; if (i == 0) { NODE *p = move(len - 1), *q = p->next; head = p->next = q->next; x = q->data; delete q; } else { NODE *p = move(i - 1), *q = p->next; p->next = q->next; x = q->data; delete q; } len--; insert(len, x); }
void get_length() { cout << len << endl; }
void query(int i) { if (i < 0 || i >= len) { cout << -1 << endl; return; } cout << move(i)->data << endl; }
void get_max() { NODE *p = head; int k = -1; for (int i = 0; i < len; i++) { if (p->data > k) k = p->data; p = p->next; } cout << k << endl; }
void clear() { NODE *p = head, *q; for (int i = 0; i < len; i++) { q = p->next; delete p; p = q; } } }
|