#include <iostream>
#include <algorithm>
using namespace std;
struct vector {
vector *nextElem;
int ans;
int length;
vector(int n) {
this->ans = 0;
vector *next = nextElem;
for (int i=0; i<=n; i++){
next->ans=0;
next=next->nextElem;
}
length = n;
}
vector(int n, int val) {
this->ans = val;
vector *next = nextElem;
for (int i=0; i<=n; i++){
next->ans=val;
next=next->nextElem;
}
length = n;
}
void push_back(int val) {
vector *next = nextElem;
for (int i = 1; i < length; i++) {
next=next->nextElem;
}
length++;
next->ans = val;
}
void pop_back() {
vector *next = nextElem;
for (int i = 0; i < length; i++) {
next=next->nextElem;
}
length--;
next->nextElem=0;
}
int get(int i) {
vector *next = nextElem;
if (i > 0) {
for (int j = 1; j < i; j++) {
next=next->nextElem;
}
return next->ans;
} else return ans;
}
int size() {
return length;
}
};
int main() {
vector *v;
v = new vector(2, 10);
v->push_back(0);
std::cout << v->size() << std::endl; // 3
std::cout << v->get(2) << std::endl; // 0
std::cout << v->get(1) << std::endl; // 10
std::cout << std::endl;
v->pop_back();
v->pop_back();
std::cout << v->size() << std::endl; // 1
std::cout << std::endl;
v->push_back(5);
v->push_back(17);
v->push_back(3);
std::cout << v->get(0) << std::endl; // 10
std::cout << v->get(1) << std::endl; // 5
std::cout << v->get(3) << std::endl; // 3
std::cout << v->size() << std::endl; // 4
}
带一个参数的构造函数会创建一个包含 n 个元素的堆栈,其值为 0;有两个参数 - 值为 val。push_back 和 pop_back 方法在堆栈上创建和删除元素。get方法通过i参数返回元素的值,size也返回序列中元素的个数。项目计数从 0 开始。
一切似乎都运行良好,但执行后,Code::Blocks 显示消息Process returned -1073741571 (0xC00000FD) execution time : 1.473 s。帮助
重写了动态数组的所有内容