概念理解:
栈:逻辑结构
链栈:使用链式存储方式实现的栈
链栈的操作与链表类似,入栈和出栈是在链表的表头进行
推荐使用不带头结点的链表实现栈
链栈结构体:
//栈的链式存储结构
typedef struct LNode{
//数据域
int data;
//指针域
struct LNode* next;
} LNode,*LinkStack;
初始化链栈:
//初始化链栈
bool InitStack(LinkStack &L){
L = NULL;
return true;
}
判栈空:
//判栈空
bool StackEmpty(LinkStack L){
if(L == NULL){
return true;
}
return false;
}
入栈:
//入栈
bool Push(LinkStack &L,int x){
//动态创建结点,返回指向该结点的指针
LNode* s = (LNode*)malloc(sizeof(LNode));
//为结点数据域赋值
s->data = x;
//判断栈是否为空,并使用头插法
if(L == NULL){
s->next = NULL;
}else{
s->next = L;
}
//头指针指向新入栈结点
L = s;
return true;
}
出栈:
//出栈
bool Pop(LinkStack &L){
//判栈空
if(L == NULL){
return false;
}
LNode* s = L;
L = L->next;
free(s);
return true;
}
读栈顶元素:
//读栈顶元素
LNode* GetTop(LinkStack L){
if(L == NULL){
return NULL;
}
return L;
}
测试:
#include <stdio.h>
#include <stdlib.h>//使用malloc和free关键字需要引入这个库
//栈的链式存储结构
typedef struct LNode{
//数据域
int data;
//指针域
struct LNode* next;
} LNode,*LinkStack;
//初始化链栈
bool InitStack(LinkStack &L){
L = NULL;
return true;
}
//判栈空
bool StackEmpty(LinkStack L){
if(L == NULL){
return true;
}
return false;
}
//入栈
bool Push(LinkStack &L,int x){
//动态创建结点,返回指向该结点的指针
LNode* s = (LNode*)malloc(sizeof(LNode));
//为结点数据域赋值
s->data = x;
//判断栈是否为空,并使用头插法
if(L == NULL){
s->next = NULL;
}else{
s->next = L;
}
//头指针指向新入栈结点
L = s;
return true;
}
//出栈
bool Pop(LinkStack &L){
//判栈空
if(L == NULL){
return false;
}
LNode* s = L;
L = L->next;
free(s);
return true;
}
//读栈顶元素
LNode* GetTop(LinkStack L){
if(L == NULL){
return NULL;
}
return L;
}
//打印栈
void Print(LinkStack L){
LNode* p = L;
printf("栈内元素:");
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(){
//声明一个结构体类型的链栈元素
LinkStack L;
//初始化
InitStack(L);
printf("当前栈是否为空:%d\n",StackEmpty(L));
//入栈
Push(L,3);
Push(L,2);
Push(L,1);
printf("当前栈是否为空:%d\n",StackEmpty(L));
//读栈顶元素
LNode* s = NULL;
s = GetTop(L);
printf("当前栈顶元素:%d\n",s->data);
//出栈
Pop(L);
printf("出栈执行!\n");
s = GetTop(L);
printf("当前栈顶元素:%d\n",s->data);
//打印栈
Print(L);
}