文章目錄
- Stack概念
- Stack實作
Stack概念
??堆疊是一種特殊的線性表,其中只允許在固定的一端進行插入和洗掉元素操作的一端稱為堆疊頂,另一端稱為堆疊底,遵循LIFO(last in first out)原則,
Stack實作
Stack.h檔案
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int SLDataType;
typedef struct SeqList
{
SLDataType* a;
int top;
int capacity;
}Stack;
//堆疊的初始化
void StackInit(Stack* pst);
//堆疊的銷毀
void StackDestory(Stack* pst);
//增加堆疊頂元素
void StackPush(Stack* pst, SLDataType x);
//移除堆疊頂元素
void StackPop(Stack* pst);
//回傳堆疊中元素的數目
int StackSize(Stack* pst);
//回傳堆疊頂元素
SLDataType StackTop(Stack* pst);
//堆疊內判空
int StackEmpty(Stack* pst);
Stack.c檔案
#include "Stack.h"
//堆疊的初始化
void StackInit(Stack* pst)
{
assert(pst);
pst->a = (SLDataType*)malloc(sizeof(SLDataType)* 4);
pst->top = 0;
pst->capacity = 4;
}
//堆疊的銷毀
void StackDestory(Stack* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capacity = 0;
}
//增加堆疊頂元素
void StackPush(Stack* pst, SLDataType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
SLDataType* tmp = realloc(pst->a, pst->capacity * 2 * sizeof(SLDataType));
if (tmp == NULL)
{
printf("relloc fail\n");
exit(-1);
}
pst->a = tmp;
pst->capacity *= 2;
}
pst->a[pst->top] = x;
pst->top++;
}
//移除堆疊頂元素
void StackPop(Stack* pst)
{
assert(pst);
assert(!StackEmpty(pst));
pst->top--;
}
//回傳堆疊中元素的數目
int StackSize(Stack* pst)
{
assert(pst);
return pst->top;
}
//回傳堆疊頂元素
SLDataType StackTop(Stack* pst)
{
assert(pst);
assert(!StackEmpty(pst));
return pst->a[pst->top - 1];
}
//堆疊內判空
int StackEmpty(Stack* pst)
{
assert(pst);
return pst->top == 0 ? 1 : 0;
}
Test.c
#include "Stack.h"
int main()
{
Stack st;
StackInit(&st);
StackPush(&st, 1);
StackPush(&st, 2);
StackPush(&st, 3);
StackPush(&st, 4);
while (!StackEmpty(&st))
{
printf("%d ", StackTop(&st));
StackPop(&st);
}
printf("\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/266407.html
標籤:其他
上一篇:Python中串列常用方法總結
