以下代码是基于C语言写的堆栈的压栈,出栈,清栈,读栈指针等方法,在Visual studio 中,可直接使用,供学习者参考学习。
#include<cStack.h>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include
#define MAX_SIZE 100
typedef struct Stack
{
char *data;
int size;
int top;
};
#endif
//init stack
void initStack(Stack s)
{
s->data = (char)malloc(MAX_SIZE * sizeof(char)); //分配最大内存空间
if (!s->data)
exit(OVERFLOW); //提前终止程序
s->size = MAX_SIZE;
s->top = -1;
}
void destroyStack(Stack *s)
{
free(s->data);
}
bool push(Stack *s, char ch)
{
if ((s->top + 1) != s->size)
{
s->data[++s->top] = ch;
return true;
}
else
return false;
}
char pop(Stack *s)
{
if (s->top != -1)
return s->data[s->top–];
}
char gettop(Stack *s)
{
return s->data[s->top];
}
bool isEmpty(Stack *s)
{
if (s->top == -1)
return true;
else
return false;
}
bool isFull(Stack *s)
{
if ((s->top + 1) == s->size)
return true;
else
return false;
}
void setNull(Stack *s)
{
s->top = -1;
}
int main()
{
char chd;
bool c;
Stack s1;
initStack(&s1);
c = push(&s1, ‘a’);
printf(“Stack s1 push status is %d,s.data is %c,top value is %d\n”, c,s1.data[s1.top],s1.top);
c = push(&s1, ‘b’);
printf(“Stack s1 push status is %d,s.data is %c,top value is %d\n”, c, s1.data[s1.top], s1.top);
chd = gettop(&s1);
printf(“Stack s1->top data:%c,top value is %d\n”, chd, s1.top);
chd = pop(&s1);
printf(“Stack 弹出 data:%c,top value is %d\n”, chd, s1.top);
chd = pop(&s1);
printf(“Stack 弹出 data:%c,top value is %d\n”, chd, s1.top);
c = isEmpty(&s1);
printf(“Stack s1 c bool:%d,top value is %d\n”, c, s1.top);
c = isFull(&s1);
printf(“Stack s1 c bool:%d,top value is %d\n”, c, s1.top);
return 0;
}