栈:一种特殊的线性表,其只允许在固定的一段进行插入和删除元素,进行插入和删除元素的一端叫做栈顶,另一端叫做栈底,栈中的元素遵守着先进后出的原则
 stack.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
   | #define _CRT_SECURE_NO_WARNINGS 1 #pragma once #include<stdio.h> #include<stdbool.h> #include<assert.h> #include<stdlib.h> typedef int stdata;
  typedef struct Stack { 	stdata* a; 	 	int top; 	int capacity; }st;
 
 
  void stackinit(st *ps);
  void stackdestroy(st*ps);
 
  void stackcheckcapacity(st*ps);
 
 
  void stackpush(st*ps,stdata x);
 
 
  void stackpop(st *ps);
  stdata stacktop(st*ps);
  int stacksize(st *ps);
  bool stackempty(st*ps);
 
  | 
 
 stack.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
   | #define _CRT_SECURE_NO_WARNINGS 1 #include"stack.h"
 
 
  void stackinit(st *ps) { 	assert(ps); 	ps->a = malloc(sizeof(stdata)*4); 	 	if (ps->a == NULL) 	{ 		perror("malllc"); 		return; 	} 	ps->capacity = 0; 	ps->top=0; 	 }
  void stackcheckcapacity(st*ps) { 	if (ps->top == ps->capacity) 	{ 		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity; 		 		stdata*tmp = (stdata*)realloc(ps->a, sizeof(st)*newcapacity * 2); 		if (tmp == NULL) 		{ 			perror("realllc"); 			return; 		} 		else 		{ 			ps->a = tmp; 			ps->capacity = newcapacity; 		} 	}  }
 
 
  void stackpush(st*ps,stdata x) { 	stackcheckcapacity(ps); 	 	assert(ps); 	ps->a[ps->top] = x; 	ps->top++; }
 
  void stackpop(st*ps) { 	assert(ps); 	 	assert(ps->top > 0); 	 	ps->top--; 	 }
 
  void stackdestroy(st*ps) { 	 	assert(ps); 	free(ps->a); 	ps->a = NULL; 	 	ps->top=ps->capacity = 0;
  }
  stdata stacktop(st*ps) { 	assert(ps); 	assert(ps->top > 0); 	 	 	return ps->a[ps->top - 1]; }
 
  int stacksize(st*ps) { 	assert(ps); 	return ps->top; }
 
  bool stackempty(st*ps) { 	assert(ps); 	return ps->top == 0; 	                     }
 
  | 
 
test.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   | #define _CRT_SECURE_NO_WARNINGS 1 #include"stack.h" int main() { 	st stack; 	stackinit(&stack); 	stackpush(&stack, 1); 	stackpush(&stack, 2); 	stackpush(&stack, 3); 	stackpush(&stack, 4); 	stackpush(&stack, 5); 	stackpush(&stack, 6); 	 	while (!stackempty(&stack)) 	{ 		printf("%d ", stacktop(&stack)); 		 		stackpop(&stack);
  	} 	stackdestroy(&stack); }
 
  |