首页 > 编程 > C++ > 正文

C语言数组栈实现模板

2020-05-23 13:22:13
字体:
来源:转载
供稿:网友

本文实例为大家分享了C语言数组栈实现模板的具体代码,供大家参考,具体内容如下

SeqStack.h

#pragma once#define MAX_SIZE 1024 typedef struct SEQSTACK{ void* data[MAX_SIZE]; int size;}SeqStack; SeqStack* Init_SeqStack();      // 初始化栈void Push_SeqStack(SeqStack* stack, void* data); // 入栈void* Top_SeqStack(SeqStack* stack);    // 返回栈顶元素void Pop_SeqStack(SeqStack* stack);    // 出栈int IsEmpty(SeqStack* stack);     // 判断是否为空int Size_SeqStack(SeqStack* stack);    // 返回栈中元素的个数void Clear_SeqStack(SeqStack* stack);   // 清空栈void FreeSpace_SeqStack(SeqStack* stack);  // 销毁栈

SeqStack.cpp 函数实现

#include "SeqStack.h"#include <stdio.h>#include <stdlib.h> SeqStack* Init_SeqStack(){ SeqStack* stack = (SeqStack*)malloc(sizeof(SeqStack)); for (int i = 0; i < MAX_SIZE; i++) { stack->data[i] = NULL; } stack->size = 0;  return stack;} void Push_SeqStack(SeqStack* stack, void* data){ if (stack == NULL) return; if (stack->size == MAX_SIZE)  // 栈为满 return; if (data == NULL) return;  stack->data[stack->size] = data; stack->size++;} void* Top_SeqStack(SeqStack* stack)    // 返回栈顶元素,不弹出{ if (stack == NULL) return NULL; if (stack->size == 0) return NULL;  return stack->data[stack->size - 1];} void Pop_SeqStack(SeqStack* stack)    // 出栈{ if (stack == NULL) return;  if (stack->size == 0) return; stack->data[stack->size - 1] = NULL; stack->size--;} int IsEmpty(SeqStack* stack)     // 判断是否为空{ if (stack == NULL) return -1;  if (stack->size == 0) return 1;  return 0; } int Size_SeqStack(SeqStack* stack){ if (stack == NULL) return -1;  return stack->size;} void Clear_SeqStack(SeqStack* stack){ if (stack == NULL) return;  for (int i = 0; i < stack->size; i++) { stack->data[i] = NULL; }  stack->size = 0;} void FreeSpace_SeqStack(SeqStack* stack){ if (stack == NULL) return;  free(stack);}

数组栈测试程序

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>#include "SeqStack.h" typedef struct PERSON{ char name[64]; int age;}Person; int main(){ SeqStack* stack = Init_SeqStack();  // 创建栈  Person p1, p2, p3, p4, p5; strcpy(p1.name, "aaa"); strcpy(p2.name, "bbb"); strcpy(p3.name, "ccc"); strcpy(p4.name, "ddd"); strcpy(p5.name, "eee");  p1.age = 10; p2.age = 20; p3.age = 30; p4.age = 40; p5.age = 50;  Push_SeqStack(stack, &p1);     // 入栈 Push_SeqStack(stack, &p2); Push_SeqStack(stack, &p3); Push_SeqStack(stack, &p4); Push_SeqStack(stack, &p5);  while (Size_SeqStack(stack) > 0) { Person* person = (Person*)Top_SeqStack(stack); printf("Name:%s Age:%d/n", person->name, person->age); Pop_SeqStack(stack); }  // 释放内存 FreeSpace_SeqStack(stack); system("pause");}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表