1.概念
棧是一種遵循先進後出的特殊線性表。
入數據只能從棧頂入,出數據只能從棧頂出。
所以實現棧,通過數組實現最優,因爲總是從最後一個拿出數據。
2.代碼展示
Stack.h
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
// 支持動態增長的棧
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 棧頂
int _capacity; // 容量
}Stack;
// 初始化棧
void StackInit(Stack* ps);
// 入棧
void StackPush(Stack* ps, STDataType data);
// 出棧
void StackPop(Stack* ps);
// 獲取棧頂元素
STDataType StackTop(Stack* ps);
// 獲取棧中有效元素個數
int StackSize(Stack* ps);
// 檢測棧是否爲空,如果爲空返回非零結果,如果不爲空返回0
int StackEmpty(Stack* ps);
// 銷燬棧
void StackDestroy(Stack* ps);
Stack.c
#include"Stack.h"
// 初始化棧
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
// 入棧
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->_capacity == ps->_top)//檢查容量,擴容
{
int newcapcity = ps->_capacity == 0 ? 2 : 2 * ps->_capacity;
ps->_a = (STDataType*)realloc(ps->_a,newcapcity*sizeof(STDataType));
ps->_capacity = newcapcity;
}
ps->_a[ps->_top++] = data;
}
// 出棧
void StackPop(Stack* ps)
{
assert(ps && ps->_top>0);
--ps->_top;
}
// 獲取棧頂元素
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top-1];
}
// 獲取棧中有效元素個數
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
// 檢測棧是否爲空,如果爲空返回非零結果,如果不爲空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
if (ps->_top == 0)
{
return 0;
}
else
{
return 1;
}
}
// 銷燬棧
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
void test()
{
Stack s;
StackInit(&s);
StackPush(&s, 1);
StackPush(&s, 2);
StackPop(&s);
StackPush(&s, 3);
StackPush(&s, 4);
while (StackEmpty(&s) != 0)
{
printf("%d ",StackTop(&s));
StackPop(&s);
}
StackDestroy(&s);
}
test.c
#include"Stack.h"
int main()
{
test();
system("pause");
return 0;
}
3.結果展示
4.心得體會
空棧top爲0,注意檢查容量。