数据结构——栈

创建类型

typedef int StackTypeDate;
typedef struct stack
{
StackTypeDate* arr;
int top;
int capacity;
}Stack;

初始栈

void InitStack(Stack* ps)
{
assert(ps);
ps->arr = NULL;
ps->top = ps->capacity = 0;
}

压栈

void StackPush(Stack* ps, StackTypeDate x)
{
assert(ps);

if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
ps->arr = (StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate) * newcapacity);
ps->capacity = newcapacity;
}

ps->arr[ps->top] = x;
ps->top++;
}


出栈

void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}

察看栈顶的元素

StackTypeDate StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
//注意这里的减一
return ps->arr[ps->top-1];
}

栈的个数

int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}

栈是否为空

bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->capacity == 0;
}

栈的销毁

void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}

|
16天前
|

33 4
|
2天前
|

11 3
|
10天前
|

【数据结构】栈和队列的模拟实现（两个方式实现）
【数据结构】栈和队列的模拟实现（两个方式实现）
10 1
|
2天前

7 1
|
7天前
|

11 0
|
7天前
|

14 2
|
7天前
|

13 0
|
7天前
|

9 0
|
7天前
|

4 0
|
7天前
|

6 0