本人很菜,如有bug請指出!
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#define MAX_SIZE 50;
using namespace std;
typedef int status;
typedef int Elmetype;
typedef struct
{
Elmetype *top;
Elmetype *bottom;
int size;
} Stack;
//初始化棧
status InitStack(Stack *S)
{
S->bottom = (Elmetype *)malloc(sizeof(Elmetype) * S->size);
if(!S->bottom)
return -1;
S->top = S->bottom;
S->size = MAX_SIZE;
return 1;
}
//入棧
status PUSH(Stack *S, Elmetype e)
{
*(S->top) = e;
S->top++;
return 1;
}
//出棧e來存放出棧的元素
status POP(Stack *S, Elmetype *e)
{
if(S->top > S->bottom)
*e = *(--S->top);
else
return -1;
return 1;
}
//返回棧的長度
int StackLen(Stack *S)
{
return S->top - S->bottom;
}
//獲得棧頂元素
int getTop(Stack *S)
{
return *(S->top - 1);
}
//清空棧
status ClearStack(Stack *S)
{
S->top = S->bottom;
return 1;
}
//銷燬棧
status DestoryStack(Stack *S)
{
delete(S->bottom);
return 1;
}
//判斷棧是否爲空
status isEmpty(Stack *S)
{
if(S->top == S->bottom)
return 1;
else
return -1;
}
//輸出棧中元素,棧底到棧頂
void PrintStack(Stack *S)
{
Elmetype *i;
i = S->bottom;
while(i < S->top)
{
cout << *(i) << "\t";
i++;
}
cout << endl;
}
//逆序輸c出棧中元素,等於正常出棧的順序
void PrintStackReverse(Stack *S)
{
Elmetype *i;
i = S->top - 1;
while(i >= S->bottom)
{
cout << *(i) << "\t";
i--;
}
cout << endl;
}
int main()
{
Stack S;
Elmetype e;
status i;
InitStack(&S);
cout << "請輸入要入棧元素:";
while(cin >> e)
PUSH(&S, e);
PrintStack(&S);
PrintStackReverse(&S);
POP(&S, &e);
cout << "出棧元素爲:" << e << endl;;
cout << "棧的長度爲:" << StackLen(&S) << endl;
cout << "棧頂元素爲:" << getTop(&S) << endl;
i = isEmpty(&S);
if(i)
cout << "棧爲空\n";
else
cout << "棧不爲空\n";
ClearStack(&S);
i = isEmpty(&S);
if(i == 1)
cout << "棧爲空\n";
else
cout << "棧不爲空\n";
DestoryStack(&S);
//cout<<"棧頂元素爲:"<<getTop(&S)<<endl;
//cout<<*(S.bottom);
return 0;
}