目錄
(一)順序棧圖文解析
順序棧是指利用順序存儲結構實現的棧,,即利用一組地址連續的存儲單位(數組)依次存放自棧底base到棧頂top的數據元素,同時設置指針top表示棧頂元素在順序棧中的位置。
用簡潔的話來講
順序棧不像順序表,順序棧只能從上往下一個個的網數組添加數據,出來也只能從上往下一個一個取出來。
其中棧底base爲數組空間,而棧頂top作爲一個指針爲棧頂確定位置,每添加一個數據,top加一,每減少一個,top減一。
(二) 順序棧代碼解析
(1) 順序棧的基本操作
1.1 順序棧的存儲結構
#define MAXSIZE 100
typedef struct
{
int *base; //棧底指針,指向棧底
int *top; //棧頂指針,指向棧頂
int stacksize; //棧的最大容量
}SqStack;
1.2 初始化順序棧
void InitStack(SqStack &S)
{
S.base=(int*)malloc(MAXSIZE*sizeof(int));//爲順序棧的棧底分配一個最大容量爲MAXSIZE的空間
if(S.base)
printf("內存分配成功\n");
S.top=S.base; //空棧,即棧底等於棧頂
S.stacksize=MAXSIZE; //棧的最大容量
}
1.3順序棧的入棧
void Push(SqStack &S,int e)
{
if(S.top-S.base==S.stacksize)//棧滿時棧頂到棧頂之間的空間等於棧的最大容量
printf("棧滿!");
else //棧頂自加一
*(S.top++)=e;//先*S.top=e,然後S.top++
}
1.4 順序棧的出棧
void Pop(SqStack &S,int &e)
{
if(S.top==S.base)//當棧頂等於棧底,則棧爲空
printf("棧空");
else //棧頂自減一
e=*(--S.top);//先S.top--,然後e=*S.top
}
1.5 取棧頂元素
void GetTop(SqStack S)
{
if(S.top!=S.base)
printf("%d",*(S.top-1));//輸出棧頂所指位置的下面一個數據元素
}
(2) 順序棧源代碼及測試
2.1 源代碼
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
typedef struct
{
int *base;
int *top;
int stacksize;
}SqStack;
void InitStack(SqStack &S)
{
S.base=(int*)malloc(MAXSIZE*sizeof(int));
if(S.base)
printf("內存分配成功\n");
S.top=S.base;
S.stacksize=MAXSIZE;
}
void Push(SqStack &S,int e)
{
if(S.top-S.base==S.stacksize)
printf("棧滿!");
else
*(S.top++)=e;
}
void Pop(SqStack &S,int &e)
{
if(S.top==S.base)
printf("棧空");
else
e=*(--S.top);
}
void GetTop(SqStack S)
{
if(S.top!=S.base)
printf("棧頂:%d\n",*(S.top-1));
}
int main()
{
SqStack S;
int e;
InitStack(S);
Push(S,10);
Push(S,20);
Push(S,30);
printf("入棧10 20 30\n");
GetTop(S);
Pop(S,e);
printf("出棧一次\n");
GetTop(S);
return 0;
}
2.2 測試結果
測試環境 : Windows 10
編譯軟件 : Visual C++ 6.0