當前位置:編程學習大全網 - 源碼下載 - C++, 順序棧在main函數中怎麽實現出棧,並輸出出棧結果?求教,代碼如下:

C++, 順序棧在main函數中怎麽實現出棧,並輸出出棧結果?求教,代碼如下:

妳的判斷棧是否為空需要返回值,然後就好辦了。Pop的話用引用傳遞取回棧頂的值,所以沒用GetTop。

#include?<iostream>

#include?<stdio.h>

#include?<malloc.h>

using?namespace?std;

#define?OK?1

#define?ERROR?0

#define?OVERFLOW?-2

#define?MAXSIZE?100

#define?exit

typedef?char?ElemType;

typedef?struct

{

ElemType?*base;//棧底指針

ElemType?*top;//棧頂指針

int?stacksize;//棧可用的最大容量

}?SqStack;

void?InitStack(SqStack?&S)

{

//構造壹個空棧S

S.base?=?new?ElemType[MAXSIZE];

if?(!S.base)

exit(OVERFLOW);

S.top?=?S.base;

S.stacksize?=?MAXSIZE;

}

bool?StackEmpty(SqStack?&S)?//判斷棧是否為空

{

if(S.top==S.base)

{

printf("順序棧為空\n");

return?true;

}

else

{

printf("順序棧為非空\n");

return?false;

}

}

bool?Push(SqStack?&S,ElemType?e?)//順序棧進棧

{

if(S.top-S.base==S.stacksize)

return?ERROR;

*S.top++=e;

return?OK;

}

bool?Pop(SqStack?&S,ElemType?&e)?//順序棧出棧

{

if(S.top==S.base)

return?ERROR;

e=*--S.top;

return?OK;

}

void?DestroyStack(SqStack?&S)?//銷毀

{

free(S.base);

printf("順序棧已銷毀");

}

bool?GetTop(SqStack?&S)?//取棧頂元素

{

if(S.top!=S.base)

return?*(S.top-1);

}

void?InitStack(SqStack?&S);

bool?StackEmpty(SqStack?&S);

bool?Push(SqStack?&S,ElemType?e?);

bool?Pop(SqStack?&S,ElemType?&e);

void?DestroyStack(SqStack?&S);

bool?GetTop(SqStack?&S,ElemType?&e);

int?main()

{

SqStack?S;

ElemType?e;

InitStack(S);

printf("順序棧已初始化\n");

StackEmpty(S);

Push(S,'a');

Push(S,'b');

Push(S,'c');

Push(S,'d');

Push(S,'e');

printf("已插入元素a,b,c,d,e,判斷棧是否為空?\n");

StackEmpty(S);

/***

將順序棧S棧內的

全部元素出棧,並

輸出出棧結果,求教!

***/

while(!StackEmpty(S))

{

ElemType?e;

Pop(S,?e);

printf("取出元素%c?\n",?e);

}

}

  • 上一篇:最打動心的微信表白語錄
  • 下一篇:1997年有什麽網絡遊戲了?好玩嗎?
  • copyright 2024編程學習大全網