顺序栈是一种特殊的顺序表,主要操作是入栈和出栈。将顺序表加一些特定限制,就成了顺序栈。
注:
1.顺序栈C语言实现;
2.按较简单的方式实现,主要帮助理解,可在此基础上修改,更加完善;
3.提供几个简单函数,可自行添加功能;
4.可用C++封装。
顺序栈容量
#define CAPACITY 20 //容量
顺序栈结构体
typedef struct { int *m_pHead; //指向数组头 int m_iTop; //栈顶 int m_iCapacity; //容量 }SStack;
核心操作入栈出栈
SStack* createStack(); void push(SStack *pStack, int iElement); int pop(SStack *pStack); void showStack(SStack *pStack); void releaseMem(SStack* pStack);
创建顺序栈
SStack* createStack() { SStack *pStack = (SStack*)malloc(sizeof(SStack)); if(!pStack) { printf("动态内存分配失败!\n"); return pStack; } pStack->m_pHead = (int*)malloc(sizeof(int) * CAPACITY); if(!pStack->m_pHead) { printf("动态内存分配失败!\n"); return NULL; } pStack->m_iTop = -1; pStack->m_iCapacity = CAPACITY; return pStack; }
入栈
void push(SStack *pStack, int iElement) { if(!pStack || !pStack->m_pHead) { printf("顺序栈不存在!\n"); return; } if(pStack->m_iTop == pStack->m_iCapacity - 1) { printf("顺序栈已满!\n"); return; } pStack->m_pHead[++pStack->m_iTop] = iElement; }
出栈
int pop(SStack *pStack) { if(!pStack || !pStack->m_pHead) { printf("顺序栈不存在!\n"); return -1; } if(pStack->m_iTop < 0) { printf("顺序栈元素个数为0!\n"); return -1; } return pStack->m_pHead[pStack->m_iTop--]; }
打印
void showStack(SStack *pStack) { if(!pStack || !pStack->m_pHead) { printf("顺序栈不存在!\n"); return; } printf("容量:%d,栈顶:%d,打印元素:\n", pStack->m_iCapacity, pStack->m_iTop); for(int i = 0; i <= pStack->m_iTop; i++) printf("%d ", pStack->m_pHead[i]); printf("\n"); }
释放内存
void releaseMem(SStack* pStack) { if(!pStack) { printf("顺序栈不存在!\n"); return; } if(pStack->m_pHead) free(pStack->m_pHead); free(pStack); printf("内存释放成功!\n"); }