使用数组C++的堆栈实现



我正在尝试实现类的一些方法"堆叠";。对于push((方法,如果堆栈顶部等于容量,我将尝试复制数组的容量。顶部是下一个插槽的项目。我通过创建一个容量是原来阵列两倍的新阵列来完成这项工作,然后复制内容。我实现的所有其他方法(empty((、pop((、top(。为什么会出现这种问题?

#include <iostream>
using namespace std;
class stack
{
public:
stack();
bool empty();
void pop();
void push(int x);
int &topElem();

private:
int *buffer;
int top;                          // Top element of stack
int capacity = 10;                // Capacity of array
};
stack::stack()
{
int *val = new int[capacity];
buffer = val;
top = 0;
}
bool stack::empty()
{
if(top == 0)
return true;
else
return false;
}
void stack::push(int x)
{
if(top == capacity)
{
int *newArray = new int[capacity * 2];
for(int i = 0; i < capacity; i++)
{
newArray[i] = buffer[i];
//cout << "newArray[" << i << "]: " << newArray[i] << endl;
}
buffer = newArray;
delete[] newArray;
newArray = NULL;
}
buffer[top] = x;
top++;
}
void stack::pop()
{
if(!empty())
{
top--;
}
else
cout << "Stack is empty!" << endl;
}
int& stack::topElem()
{
return buffer[top - 1];
}
int main()
{
stack plates;

for (int i = 0; i < 20; i++)  // Add 20 elements to the stack
{
plates.push(i);
}
while (!plates.empty())
{
cout << plates.topElem() << endl;      // Prints the elemtents of the stack
plates.pop();                          // Pops the last element of the stack
}
return 0;
}

//输出1918171615141312111098.7.6.5.4.393-125022428393-1250206816

buffer = newArray;
delete[] newArray;

这并没有达到你的预期。它将buffer指向新数组,泄漏旧数组,然后删除缓冲区指向的内存。

你可能想要这样的东西:

delete[] buffer; // free the old buffer
buffer = newArray; // point it to the newly allocated memory

最新更新