代码说明
1,初始化为一个空栈. top 指向栈顶元素, 所以它的初始值为 − 1 .
2,push 的时候, 需要先改变 top 再放元素.
3,pop 的时候, 需要先改变 top 再 return.
代码:
#include<stdio.h>
#include<malloc.h>
#define STACK_MAX_SIZE 10
typedef struct CharStack
{
int top;
char data[STACK_MAX_SIZE];
}*CharStackPtr;
//输出栈
void outputStack(CharStackPtr paraStack)
{
for (int i = 0; i <= paraStack->top; i++)
{
printf("%c", paraStack->data[i]);
}
printf("\r\n");
}
//初始化空链表
CharStackPtr charStackInit()
{
CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
resultPtr->top = -1;
return resultPtr;
}
//元素进栈
void push(CharStackPtr paraStackPtr, int paraValue)
{
//1.空间确认
if (paraStackPtr->top >= STACK_MAX_SIZE - 1)
{
printf("Cannot push element:stack full\r\n");
return;
}
//2.更新顶部
paraStackPtr->top++;
//3.进栈
paraStackPtr->data[paraStackPtr->top] = paraValue;
}
//从栈中弹出元素
char pop(CharStackPtr paraStackPtr)
{
//1,空间确认
if (paraStackPtr->top < 0)
{
printf("Cannot pop element:stack empty\r\n");
return '\0';
}
//2.更新
paraStackPtr->top--;
//3.弹出元素
return paraStackPtr->data[paraStackPtr->top + 1];
}
void pushPopTest()
{
char ch;
int i;
printf("---pushPopTest begins.---\r\n");
//初始化
CharStackPtr tempStack = charStackInit();
printf("After initialization,the stack is:");
outputStack(tempStack);
//push
for (ch = 'a'; ch < 'm'; ch++)
{
printf("Pushing %c.\r\n", ch);
push(tempStack, ch);
outputStack(tempStack);
}
//pop
for (i = 0; i < 3; i++)
{
ch = pop(tempStack);
printf("Pop %c.\r\n",ch);
outputStack(tempStack);
}
printf("---pushPopTest ends.---\r\n");
}
void main()
{
pushPopTest();
}
结果: