●🧑個人主頁:你帥你先說.
●📃歡迎點贊👍關注💡收藏💖
●📖既選擇了遠方,便只顧風雨兼程,
●🤟歡迎大家有問題隨時私信我!
●🧐著作權:本文由[你帥你先說.]原創,CSDN首發,侵權必究,
🎸🎸歡迎光臨本小店🎸🎸
- 🕶?1.堆疊
- 🎩1.1堆疊的概念
- 👑1.2堆疊的實作
- 📱1.2.1堆疊的初始化
- 💻1.2.2判斷堆疊是否為空
- 🖱?1.2.3進堆疊
- 🏷?1.2.4出堆疊
- 📌1.2.5取堆疊頂元素
- 🔑1.2.5銷毀堆疊
🕶?1.堆疊
🎩1.1堆疊的概念
堆疊:一種特殊的線性表,其只允許在固定的一端進行插入和洗掉元素操作,進行資料插入和洗掉操作的一端稱為堆疊頂,另一端稱為堆疊底,堆疊中的資料元素遵守后進先出LIFO(Last In First Out)的原則,
壓堆疊:堆疊的插入操作叫做進堆疊/壓堆疊/入堆疊,入資料在堆疊頂,
出堆疊:堆疊的洗掉操作叫做出堆疊,出資料也在堆疊頂,

👑1.2堆疊的實作
堆疊的實作一般可以使用陣列或者鏈表實作,相對而言陣列的結構實作更優一些,因為陣列在尾上插入資料的代價比較小,

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
📱1.2.1堆疊的初始化
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = -1;
}
💻1.2.2判斷堆疊是否為空
bool StackEmpty(ST* ps)
{
if (ps->top == -1)
{
return true;
}
else
{
return false;
}
}
🖱?1.2.3進堆疊
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->capacity == ps->top+1)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = realloc(ps->a, sizeof(STDataType) * newCapacity);
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
ps->top++;
ps->a[ps->top] = x;
}
🏷?1.2.4出堆疊
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
📌1.2.5取堆疊頂元素
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top];
}
🔑1.2.5銷毀堆疊
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = 0;
ps->top = -1;
}
相信學完鏈表的你,堆疊對你來說是小菜一碟

這樣的文章你還不快 點贊👍關注💡收藏💖
悄悄告訴你📢:長按👍可一鍵三連
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351025.html
標籤:其他
上一篇:【Java】通過Java理解和實作——順序表和單鏈表
下一篇:函式與遞回
