帮我用c++语言完善下列代码,void InitStack(LinkStack &S) { //补全代码,创建一个空链栈S,即S为空指针 } void Push(LinkStack &S, ElemType x ) { //补全代码,创建结点,数据域为x,将该结点入栈S } Status Pop(LinkStack &S,ElemType &e) { //补全代码,若栈空则输出提示信息“栈空”,返回ERROR;否则栈顶元素存入参数e,且返回OK } Status ElemType Top(LinkStack S,ElemType &e) { //补全代码,若栈空则输出提示信息“栈空”,返回ERROR;否则栈顶元素存入参数e,且返回OK } bool StackEmpty(LinkStack S) { //判断栈S是否为空栈,如果是空栈,则返回true,否则返回false }
时间: 2024-02-11 18:05:04 浏览: 67
完善的代码如下:
```
#include <iostream>
using namespace std;
typedef int ElemType; // 假设栈中元素均为整型
typedef struct StackNode {
ElemType data; // 数据域
struct StackNode *next; // 指向下一个结点的指针
} *LinkStack;
// 创建一个空链栈S,即S为空指针
void InitStack(LinkStack &S) {
S = NULL;
}
// 创建结点,数据域为x,将该结点入栈S
void Push(LinkStack &S, ElemType x) {
StackNode *p = new StackNode;
p->data = x;
p->next = S;
S = p;
}
// 若栈空则输出提示信息“栈空”,返回ERROR;否则栈顶元素存入参数e,且返回OK
status Pop(LinkStack &S, ElemType &e) {
if (S == NULL) {
cout << "栈空" << endl;
return ERROR;
}
e = S->data;
StackNode *p = S;
S = S->next;
delete p;
return OK;
}
// 若栈空则输出提示信息“栈空”,返回ERROR;否则栈顶元素存入参数e,且返回OK
status Top(LinkStack S, ElemType &e) {
if (S == NULL) {
cout << "栈空" << endl;
return ERROR;
}
e = S->data;
return OK;
}
// 判断栈S是否为空栈,如果是空栈,则返回true,否则返回false
bool StackEmpty(LinkStack S) {
if (S == NULL) {
return true;
}
return false;
}
int main() {
LinkStack S;
InitStack(S);
Push(S, 1);
Push(S, 2);
Push(S, 3);
ElemType e;
Pop(S, e);
cout << "弹出的元素为:" << e << endl;
Top(S, e);
cout << "栈顶元素为:" << e << endl;
if (StackEmpty(S)) {
cout << "栈为空" << endl;
} else {
cout << "栈不为空" << endl;
}
return 0;
}
```
阅读全文