栈基本操作实现
# include <stdio.h>
# include <stdlib.h>
struct Stack{
char data;
struct Stack * next;
};
typedef struct Stack Stack;
//初始化函数 使栈底指针为NULL
void initStack(Stack * S)
{
S->next = NULL;
}
//向栈插入元素
void push(Stack * S,char item)
{
Stack * p = (Stack *)malloc(sizeof(Stack));
p->data = item;
p->next = S->next;
S->next = p;
}
//删除栈顶元素,并返回删除的元素
int pop(Stack *S)
{
//先判断是否为空
if(S->next == NULL)
{
// printf("栈为空!");
exit (1);//这让整个程序退出执行,故当栈为空时,多个pop函数只执行一次printf栈为空
}
else
{
Stack *p = S->next;
char x = p->data;
S->next = p->next;
free(p);
return x;
}
}
//读取栈顶元素
int peek(Stack * S)
{
if(S->next == NULL)
{
printf("栈为空!");
}
else
{
return S->next->data;
}
}
//判断栈是否为空
int isempty(Stack *S)
{
return (S->next == NULL);
}
//清空栈
void clear(Stack *S)
{
Stack * p = S->next;
while(p != NULL)
{
Stack * q = p-> next;//若不设置q直接用 S->next 不行,不知道为什么
free(p);
p = q;
}
S->next = NULL;//这个很重要不能忘
}
/*
int main()
{
int b[5] = {1,2,3,4,5};
Stack a,*S;
S = &a;
initStack(S);
for(int i = 0;i < 5;i++)
{
push(S,b[i]);
}
printf("%d\n", peek(S));
clear(S);
printf("%d\n", pop(S));
printf("%d\n", pop(S));
printf("%d\n", pop(S));
return 0;
}
*/
反思与收获
刚开始一直不理解init函数有什么用 后来运行一直报错显示访问越界,才明白了,目的是使栈顶元素指针域始终为NULL
通过编写栈,我学习了如何调试程序!