c语言:链栈的实现

来源:互联网 发布:linux open 返回值 编辑:程序博客网 时间:2024/05/18 01:49
#include<iostream>#include<stdio.h>#include<math.h>#define LEN sizeof(struct LNode)using namespace std;typedef struct LNode{int data;struct LNode *next;}LNode;typedef struct LinkStack{LNode *top;}LinkStack;//函数申明void Error(char *s);             //错误处理函数void Gettop_stack(LinkStack *s, int e); //取栈顶元素int Empty_stack(LinkStack *s);    //判断该链栈是否为空void Push_stack(LinkStack *s, int e);   //压栈函数void Pop_stack(LinkStack *s, int e);     //出栈函数//函数定义void Error(char *s){cout << s << endl;exit(1);}void Gettop_stack(LinkStack *s, int e){if (s->top == NULL)Error("该链栈为空栈!");elsee = s->top->data;cout << "该栈顶元素是:" << e << endl;}int Empty_stack(LinkStack *s){if (s->top == NULL)return 1;elsereturn 0;}void Push_stack(LinkStack *s, int e){LNode *p;p = (struct LNode*)malloc(LEN);if (!p)Error("内存分配失败");p->data = e;p->next = s->top;s->top = p;}void Pop_stack(LinkStack *s, int e){LNode *p;if (s->top==NULL)exit(1);e = s->top->data;p = s->top;s->top = s->top->next;cout << e << " ";free(p);}int main(){LinkStack p;p.top = NULL;int e = 0;Push_stack(&p, 9);Push_stack(&p, 8);Push_stack(&p, 11);while (p.top != NULL){Pop_stack(&p, e);}cout << endl;return 0;}

0 0
原创粉丝点击