順序堆疊是指利用順序存盤結構實作的堆疊,即用一組連續地址的存盤單元依次存放到堆疊底到堆疊頂的資料元素,
-----------------------------------------------------------------
1.順序堆疊的存盤結構:(這里以存盤整數為例)
1 typedef struct{ 2 ElemType data[MAXSIZE];//為順序堆疊分配最大容量的記憶體 3 int top; //指向堆疊頂 4 }SqStack;View Code
------------------------------------
2.基本操作
1)初始化:
1 void Initstack(SqStack &S) 2 { 3 if(!S.data) exit(-1); //判斷是否成功分配記憶體,如果S.data為NULL,則分配失敗 4 S.top = 0; //使top為零,指向堆疊底 5 }View Code
2)入堆疊:
1 Status Push(SqStack &S,ElemType e) 2 { 3 if(S.top==MAXSIZE) return ERROR; //判斷是否堆疊滿 4 S.data[S.top++] = e; //賦值 5 return OK; 6 }View Code
3)出堆疊:
1 Status Pop(SqStack &S) 2 { 3 if(S.top<=0) return ERROR; //先判斷堆疊是否空了 4 S.top--; //指標下移 5 return OK; 6 }View Code
4)獲得堆疊頂元素:
1 void getTop(SqStack S) 2 { 3 printf("堆疊頂元素是 %d\n",S.data[S.top-1]); 4 }View Code
5)遍歷(這個大都會用到,不算其基本操作):
1 void traverse(SqStack S) 2 { 3 printf("遍歷結果:\n"); 4 for(int i=0;i<S.top;i++) 5 { 6 printf("%d ",S.data[i]); 7 } 8 printf("\n"); 9 }View Code
------------------------------------------------------------------
完整代碼:
#include<stdio.h> #include<stdlib.h> #define MAXSIZE 100 #define ERROR 0 #define OK 1 typedef int Status; typedef int ElemType; typedef struct{ ElemType data[MAXSIZE];//為順序堆疊分配最大容量的記憶體 int top; //指向堆疊頂 }SqStack; void Initstack(SqStack &S) { if(!S.data) exit(-1); S.top = 0; } Status Push(SqStack &S,ElemType e) { if(S.top==MAXSIZE) return ERROR; S.data[S.top++] = e; return OK; } Status Pop(SqStack &S) { if(S.top<=0) return ERROR; S.top--; return OK; } void getTop(SqStack S) { printf("堆疊頂元素是 %d\n",S.data[S.top-1]); } void traverse(SqStack S) { printf("遍歷結果:\n"); for(int i=0;i<S.top;i++) { printf("%d ",S.data[i]); } printf("\n"); } int main() { SqStack S; Initstack(S); int n; Push(S,3); Push(S,4); Push(S,5); Push(S,7); Push(S,8); traverse(S); Pop(S); Pop(S); getTop(S); traverse(S); return 0; }View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/95063.html
標籤:C++
