#include<iostream>
using namespace std;
template<typename T>
class Stack
{
public:
Stack(int size = 0);
~Stack();
bool push(T element);
void pop(T &p);
void clearStack();
bool isFull();
bool isEmpty();
void StackTraverse();
int StackLength();
//char operator[](int index);
private:
T *m_iStack;
int m_iSize;
int m_iTop;
};
//template<typename T>
//char Stack<T>::operator[](int index)
//{
// return (char)m_iStack[index];
//}
template<typename T>
Stack<T>::Stack(int size)
{
m_iSize = size;
m_iStack = new T[m_iSize];
m_iTop = 0;
}
template<typename T>
Stack<T>::~Stack()
{
delete[]m_iStack;
m_iStack = NULL;
}
template<typename T>
bool Stack<T>::isFull()
{
return m_iTop == m_iSize ? true : false;
}
template<typename T>
bool Stack<T>::isEmpty()
{
return 0 == m_iTop ? true : false;
}
template<typename T>
void Stack<T>::pop(T &p)
{
if (!isEmpty())
{
p = m_iStack[--m_iTop];
}
}
template<typename T>
bool Stack<T>::push(T element)
{
if (isFull())
{
return false;
}
m_iStack[m_iTop++] = element;
return true;
}
template<typename T>
void Stack<T>::clearStack()
{
m_iTop = 0;
}
template<typename T>
int Stack<T>::StackLength()
{
return m_iTop;
}
template<typename T>
void Stack<T>::StackTraverse()
{
for (int i = --m_iTop; i >= 0; i--)
{
cout << m_iStack[i] ;
}
}
int main()
{
Stack<char> *p = new Stack<char>(30);
Stack<char> *pNeed = new Stack<char>(30);
char a = 0;
char N[] = "[()]";
char CurrentNeed = 0;
for (int i = 0;i < (int)strlen(N) ; i++)
{
if (N[i] != CurrentNeed)
{
p->push(N[i]);
switch (N[i])
{
case '[':
if (CurrentNeed != 0)
{
pNeed->push(CurrentNeed);
}
CurrentNeed = ']';
break;
case '(':
if (CurrentNeed != 0)
{
pNeed->push(CurrentNeed);
}
CurrentNeed = ')';
break;
}
}
else
{
char elem;
p->pop(elem);
pNeed->pop(CurrentNeed);
}
/*cout << CurrentNeed << "Current" << endl;
p->StackTraverse();
cout << "p" <<endl;
pNeed->StackTraverse();
cout << "pNeed" <<endl;*/
}
if (p->StackLength() == 0)
if (pNeed->StackLength() == 0)
cout << "匹配" << endl;
cout << "不匹配" << endl;
delete p; //断点调试
p = NULL;
delete pNeed;
pNeed = NULL;
system("pause");
return 0;
}在断点调试的时候说在p的析构函数上面发生异常,但是如果把注释的那段注释掉就不会出现问题,请问为什么?
1 回答
已采纳
onemoo
TA贡献883条经验 获得超454个赞
StackTraverse 函数中,你是不是想让 i 从 m_iTop-1 循环到 0 来依次打印整个栈?
如果是这样的话,那 for 循环的初始部分 int i = --m_iTop 就有问题了! 这样做虽然 i 确实初始化为 m_iTop-1,但是 m_iTop 也自减了!结果每调用一次 StackLength() 栈顶就同时减少一位,这不是你想要的结果吧。
事实上,105 行的 for 循环中,只要 107 行 N[i] != CurrentNeed,就会先 push——栈顶+1,后 StackLength() 又会使栈顶减 1 重新变为 0。 而只要某一次循环时 N[i] == CurrentNeed,就会调用 pop,这会访问 m_iStack[-1],恐怕这会引起问题。
- 1 回答
- 0 关注
- 1156 浏览
添加回答
举报
0/150
提交
取消