方便以後使用以及擴充功能 將此程式紀錄在這
struct CH {
char ch;
int num;
CH *next;
};
class stack
{
public:
stack();
~stack();
void push(char ch); //放入最上層
void push(int num);
void pop(); // 移除最上層
char top(); // 取得最上層
int num_top();
void print(); // 印出stack
bool isEmpty();
void clear(); // 將stack裡的所有資料清空 釋放記憶體
private:
CH *ch_head;
CH *ch_cur;
int first;
};
stack::stack()
{
first = 0;
}
stack::~stack()
{
}
bool stack::isEmpty() {
if (first == 0)
return true;
else
return false;
}
void stack::clear() {
while (!isEmpty()) {
pop();
}
}
void stack::push(char ch) {
if (first == 0) {
ch_head = new CH;
ch_cur = ch_head;
ch_cur->ch = ch;
ch_cur->next = NULL;
first++;
}
else {
CH *newPtr = new CH;
ch_cur->next = newPtr;
ch_cur = newPtr;
ch_cur->ch = ch;
ch_cur->next = NULL;
}
}
void stack::push(int num) {
if (first == 0) {
ch_head = new CH;
ch_cur = ch_head;
ch_cur->num = num;
ch_cur->next = NULL;
first++;
}
else {
CH *newPtr = new CH;
ch_cur->next = newPtr;
ch_cur = newPtr;
ch_cur->num = num;
ch_cur->next = NULL;
}
}
void stack::pop() {
if (!isEmpty()) {
if (ch_head == ch_cur) {
first = 0;
delete ch_head;
}
else {
CH *pre = new CH;
CH *temp;
CH *temp2;
temp2 = pre;
temp = ch_head;
while (temp != NULL && temp != ch_cur) {
if (temp->next == ch_cur)
pre = temp;
temp = temp->next;
}
temp = ch_cur;
delete temp;
ch_cur = pre;
ch_cur->next = NULL;
delete temp2;
}
}
}
char stack::top() {
if( isEmpty()){
return '\0';
}
else{
if (ch_head->next == NULL) {
return ch_head->ch;
}
else {
return ch_cur->ch;
}
}
return '\0';
}
int stack::num_top() {
if (!isEmpty()) {
if (ch_head->next == NULL) {
return ch_head->num;
}
else {
return ch_cur->num;
}
}
return 0;
}
void stack::print() {
if (!isEmpty()) {
CH *temp = new CH;
temp = ch_head;
cout << endl;
while (temp != NULL) {
cout << temp->ch << ",";
temp = temp->next;
}
}
}