赞
踩
目录
- typedef int STDataType;
- //定义栈
- //先进后出,后进先出
- typedef struct Stack
- {
- STDataType* a;
- int top;
- int capacity;
- }ST;
-
- void StackInit(ST* ps)
- {
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
-
- void StackDestroy(ST* ps)
- {
- assert(ps);
- free(ps->a);
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
- void StackPush(ST* ps, STDataType x)
- {
- //判断栈是否为空
- if (ps->capacity == ps->top)
- {
- int newcapacity = ps->capacity = ps->top == 0 ? 4 : ps->capacity * 2;
- STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)* newcapacity);
- if (tmp == NULL)
- {
- printf("realloc fail\n");
- exit(-1);
- }
- ps->a = tmp;
- ps->capacity = newcapacity;
- }
- //插入
- ps->a[ps->top] = x;
- ps->top++;
- }
- //相当于尾删
- void StackPop(ST* ps)
- {
- assert(ps);
- assert(ps->top > 0);
- ps->top--;
- }
- STDataType StackTop(ST* ps)
- {
- assert(ps);
- assert(ps->top > 0);
- return ps->a[ps->top - 1];
- }
- int StackSize(ST* ps)
- {
- return ps->top;
- }
- bool StackEmpty(ST* ps)
- {
- if (ps->top == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
函数部分
- #define _CRT_SECURE_NO_WARNINGS
-
- #include"Stack.h"
-
-
- void StackInit(ST* ps)
- {
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
-
- void StackDestroy(ST* ps)
- {
- assert(ps);
- free(ps->a);
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
-
-
- void StackPush(ST* ps, STDataType x)
- {
- //判断栈是否为空
- if (ps->capacity == ps->top)
- {
- int newcapacity = ps->capacity = ps->top == 0 ? 4 : ps->capacity * 2;
- STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)* newcapacity);
- if (tmp == NULL)
- {
- printf("realloc fail\n");
- exit(-1);
- }
- ps->a = tmp;
- ps->capacity = newcapacity;
- }
- //插入
- ps->a[ps->top] = x;
- ps->top++;
- }
-
-
- //相当于尾删
- void StackPop(ST* ps)
- {
- assert(ps);
- assert(ps->top > 0);
- ps->top--;
- }
-
- STDataType StackTop(ST* ps)
- {
- assert(ps);
- assert(ps->top > 0);
- return ps->a[ps->top - 1];
- }
-
- int StackSize(ST* ps)
- {
- return ps->top;
- }
-
- bool StackEmpty(ST* ps)
- {
- if (ps->top == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
头文件部分
- #pragma once
- #include<stdio.h>
- #include<assert.h>
- #include<stdlib.h>
- #include<stdbool.h>
-
- typedef int STDataType;
- //定义栈
- //先进后出,后进先出
- typedef struct Stack
- {
- STDataType* a;
- int top;
- int capacity;
- }ST;
-
- //初始化
- void StackInit(ST* ps);
-
- //销毁
- void StackDestroy(ST* ps);
-
- //插入
- void StackPush(ST* ps, STDataType x);
-
- //删除
- void StackPop(ST* ps);
-
- //栈顶的存放的元素
- STDataType StackTop(ST* ps);
-
- //栈的数据个数量
- int StackSize(ST* ps);
-
- //判断栈是否为空
- bool StackEmpty(ST* ps);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。