/**
* name:栈(stack)
* time:15/8/17 15:00
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//宏定义
#define NO 0
#define YES 1
#define OK 2
#define ERROR 3
#define INFEASIBLE -1
#define OVERFLOW -2
#define EMPTY -3
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode,*LinkList;
typedef struct Stack
{
LinkList top;
}Stack;
//初始化
Status initStack(Stack &stack)
{
stack.top = NULL;
return OK;
}
//判断是否为空
Status isEmpty(Stack stack)
{
if(stack.top == NULL)
{
//cout << "为空" << endl;
return YES;
}else{
//cout << "不为空" << endl;
return NO;
}
}
//进栈
Status push(Stack &stack,ElemType temp)
{
LinkList p = (LinkList )malloc(sizeof(LNode));
if(!p)
exit(OVERFLOW);
p->data = temp;
p->next = stack.top;
stack.top = p;
return OK;
}
//出栈
Status pop(Stack &stack,ElemType &e)
{
LinkList p;
e = stack.top->data;
if(isEmpty(stack) == YES)
{
cout << "栈为空" << endl;
return ERROR;
}
p = stack.top;
stack.top = stack.top->next;
free(p); //不要忘了释放空间
return OK;
}
int main(int argc, char const *argv[])
{
Stack stack;
initStack(stack);
push(stack,1);
push(stack,2);
push(stack,3);
ElemType returnVal1,returnVal2;
pop(stack,returnVal1);
cout << "returnVal1 = " << returnVal1 << endl;
pop(stack,returnVal2);
cout << "returnVal2 = " << returnVal2 << endl;
return 0;
}
//result:
//returnVal1 = 3
//returnVal2 = 2
栈
最新推荐文章于 2025-05-02 19:27:56 发布