栈的运用

来源:百度知道 编辑:UC知道 时间:2024/06/17 11:12:38
1. 有一个链栈,每个结点放一个字符。试编写一个程序,具有下列功能:
1) 从键盘输入一个字符串入栈,以“!”不入栈。
2) 遍历及显示栈中内容
3) 执行退栈操作,使栈为空。
希望大家尽快给我答案,本人急需!谢谢!

随便写写啦
struct node {
char ch;
node *next, *prev;;
};
node stk = {'!', NULL}/*用来表示栈底*/, *top = &stk/*栈顶*/;
int stk_cnt = 0;
bool push_stk(char ch) {//压栈,如果是!则返回false
if(ch == '!') {
return false;
}
top->next = new node;
top->next->ch = ch;
top->next->next = NULL;
top->next->prev = top;
top = top->next;
return true;
}
void iter_stk() {//遍历打出内容
for (node *itr = stk.next; itr != NULL; itr = itr->next) {
cout << itr->ch;
}
}
void pop_stk() {//弹栈,从后往前
for (node *itr = top; itr->ch != '!'; itr = itr->prev) {
cout << itr->ch << endl;
node *tmp = itr->prev;
delete itr;
itr = tmp;
}
}