堆栈
1.基本特征:后进先出
2.基本操作:压入(push),弹出(pop)
3.实现要点:初始化空间、栈顶指针、判空判满
实践:使用C++语言实现堆栈类,进行示例演示并且根据此堆栈类实现进制的转换。
#include <iostream>
using namespace std;
class Stack {
public:
// 构造函数中分配内存空间
Stack (size_t size = 10) :
m_data (new int[size]), m_size (size),
m_top (0) {}
// 析构函数中释放内存空间
~Stack (void) {
if (m_data) {
delete[] m_data;
m_data = NULL;
}
}
// 压入
void push (int data) {
if (full ())
throw OverFlow ();
m_data[m_top++] = data;
}
// 弹出
int pop (void) {
if (empty ())
throw UnderFlow ();
return m_data[--m_top];
}
// 判空
bool empty (void) {
return ! m_top;
}
// 判满
bool full (void) {
return m_top >= m_size;
}
private:
// 上溢异常
class OverFlow : public exception {
public:
const char* what (void) const throw () {
return "堆栈上溢!";
}
};
// 下溢异常
class UnderFlow : public exception {
public:
const char* what (void) const throw () {
return "堆栈下溢!";
}
};
int* m_data; // 数组
size_t m_size; // 容量
size_t m_top; // 栈顶
};
void printb (unsigned int numb, int base) {
Stack stack (100);
do {
stack.push (numb % base);
} while (numb /= base);
while (! stack.empty ()) {
int digit = stack.pop ();
if (digit < 10)
cout << digit;
else
cout << char (‘A‘ + (digit - 10));
}
cout << endl;
}
int main (void) {
try {
Stack stack(20);
for (int i = 0; ! stack.full (); i++)
stack.push (i);
while (! stack.empty ())
cout << stack.pop () << " ";
cout << endl;
cout << "整数:" << flush;
int numb;
cin >> numb;
cout << "进制:" << flush;
int base;
cin >> base;
cout << "结果:";
printb (numb, base);
}
catch (exception& ex) {
cout << ex.what () << endl;
return -1;
}
return 0;
}
输出结果:
时间: 2024-11-09 00:13:07