1 #include<iostream> 2 using namespace std; 3 4 typedef int Status; 5 typedef int ElemType; 6 #define OK 1 7 #define ERROR 0 8 9 10 //链栈的存储结构 11 typedef struct StackNode 12 { 13 ElemType data; //数据域 14 struct StackNode *next; //指针域 15 }StackNode,*LinkStack; 16 17 18 //初始化,构造一个空栈 19 Status InitStack(LinkStack &S) 20 { 21 S = NULL; 22 return OK; 23 } 24 25 26 //入栈 27 //在栈顶插入元素e 28 Status Push(LinkStack &S, ElemType e) 29 { 30 LinkStack p; //生成新结点 31 p = new StackNode; 32 p->data = e; 33 p->next = S; //将新结点插入栈顶 34 S = p; //修改栈顶指针为p 35 return OK; 36 } 37 38 39 //出栈 40 //删除S的栈顶元素,用e返回其值 41 Status Pop(LinkStack &S, ElemType &e) 42 { 43 LinkStack p; 44 45 if (S == NULL) //栈空 46 return ERROR; 47 48 e = S->data; //将栈顶元素赋值给e 49 p = S; //用p临时保存栈顶元素空间,以备释放 50 S = S->next; //修改栈顶指针 51 delete p; //释放原栈顶元素的空间 52 return OK; 53 } 54 55 56 //取栈顶元素 57 ElemType GetTop(LinkStack S) 58 { 59 if (S != NULL) //栈非空 60 return S->data; //返回栈顶元素的值,栈顶指针不变 61 else 62 return ERROR; 63 } 64 65 66 int main() 67 { 68 int n, x; 69 LinkStack S; 70 71 InitStack(S); 72 73 cout << "请输入链栈的元素个数:" << endl; 74 cin >> n; 75 76 cout << "请依次输入" << n << "个元素:" << endl; 77 78 while (n--) 79 { 80 cin >> x; 81 Push(S, x); 82 } 83 84 cout << "元素依次出栈:" << endl; 85 while (S != NULL) 86 { 87 cout << GetTop(S) << " "; 88 Pop(S, x); 89 } 90 91 system("pause"); 92 return 0; 93 }
原文地址:https://www.cnblogs.com/friend-A/p/9073097.html
时间: 2024-10-11 08:43:48