目录
1、准备工作
/*
类比汉诺塔 ,最上面的叫栈顶,最下面的叫栈底,每次只能从最上面拿,即 后进的先出 (LIFO)
*/
typedef int ElemTYpe;
typedef struct SNode{
struct SNode* next;
ElemTYpe data;
}SNode,*SList;
2、入栈
void Push(ElemTYpe e,SList *S){
SNode *tmp = (SNode *) malloc(sizeof(SNode));
tmp->data = e;
tmp->next = *S;
*S = tmp;
printf("%d入栈\n",tmp->data);
}
3 、获取栈顶元素
ElemTYpe Top(SList S){
if(S == NULL){
printf("栈为空,无法获取栈顶元素\n");
return 0;
}
else{
return S->data;
}
}
4、出栈
void Pop(SList *S){
SNode *tmp;
tmp = *S;
if(tmp == NULL){
printf("栈为空\n");
return;
}
*S = (*S)->next;
printf("%d出栈\n",tmp->data);
free(tmp);
}
5、判断栈空
int IsEmpty(SList S){
if(S == NULL)
return 1;
else
return 0;
}
6、打印
//传进来后S只是局部变量
void PrintList(SList S){
while (S != NULL){
printf("%d ",S->data);
S = S->next;
}
printf("\n");
}
7、完整代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElemTYpe;
typedef struct SNode{
struct SNode* next;
ElemTYpe data;
}SNode,*SList;
//压栈
void Push(ElemTYpe e,SList *S);
//获取栈顶元素
ElemTYpe Top(SList S);
//出栈
void Pop(SList *S);
//判断栈空
int IsEmpty(SList S);
//打印
void PrintList(SList S);
int main() {
SList S = NULL;
ElemTYpe e = 0;
for(int i = 1;i<6;i++){
e++;
Push(e,&S);
}
PrintList(S);
for(int i = 1;i<3;i++){
Pop(&S);
}
PrintList(S);
printf("栈顶元素为 %d\n", Top(S));
printf("栈的状态:%d (1表示为空)\n", IsEmpty(S));
return 0;
}
void Push(ElemTYpe e,SList *S){
SNode *tmp = (SNode *) malloc(sizeof(SNode));
tmp->data = e;
tmp->next = *S;
*S = tmp;
printf("%d入栈\n",tmp->data);
}
ElemTYpe Top(SList S){
if(S == NULL){
printf("栈为空,无法获取栈顶元素\n");
return 0;
}
else{
return S->data;
}
}
int IsEmpty(SList S){
if(S == NULL)
return 1;
else
return 0;
}
void Pop(SList *S){
SNode *tmp;
tmp = *S;
if(tmp == NULL){
printf("无法出栈,栈为空\n");
return;
}
*S = (*S)->next;
printf("%d出栈\n",tmp->data);
free(tmp);
}
void PrintList(SList S){
while (S != NULL){
printf("%d ",S->data);
S = S->next;
}
printf("\n");
}
封面来自百度