考研《链栈的代码实现》两种情况:不带头结点和带头结点
栈的链式存储–不带头结点
代码:
/*
这个代码主要写了 栈的链式存储--不带头结点(recommend)
主要实现的功能有:
1. 初始化
2. 进栈、出栈、获取栈顶元素
3. 判空
4. 链栈的结构体定义
*/
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
typedef int ElemType;
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode, *LinkStack;
// 初始化
void InitLiStack(LinkStack &S){
S = NULL;
}
// 判断链栈为空
bool EmptyLiStack(LinkStack S){
//if (S == NULL)
// return true;
//else
// return false;
return S == NULL;
}
// 进栈
bool Push(LinkStack &S, ElemType x){
LinkNode* q = (LinkNode*)malloc(sizeof(LinkNode));
if (q == NULL)
return false; // 内存分配失败
q->data = x;
q->next = S;
S = q;
return true;
}
// 出栈
bool Pop(LinkStack &S, ElemType &x){
if (S == NULL)
return false;
x = S->data;
S = S->next;
return true;
}
// 获取栈顶元素
bool GetTop(LinkStack S, ElemType &x){
if (S == NULL)
return false;
x = S->data;
return true;
}
int main(){
LinkStack S;
InitLiStack(S);
Push(S,2);
Push(S,1);
Push(S,3);
int x = 0;
GetTop(S,x);
printf("x = %d\n", x); // 3
Pop(S, x);
printf("出栈的元素是:%d\n", x); //3
GetTop(S,x);
printf("出栈一个元素后的栈顶元素是:%d\n", x); // 1
return 0;
}
栈的链式存储–带头结点
代码:
/*
这个代码主要写了 栈的链式存储-- 带头结点
主要实现的功能有:
1. 初始化
2. 进栈、出栈、获取栈顶元素
3. 判空
4. 链栈的结构体定义
*/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
typedef int ElemType;
// 链栈结构体的定义(带头节点)
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode, *LinkStack;
// 初始化
bool InitLinkStack(LinkStack& S){
S = (LinkNode*)malloc(sizeof(LinkNode));
if(S == NULL)
return false;
S->next = NULL;
return true;
}
// 进栈
bool Push(LinkStack &S, ElemType x){
LinkNode* q = (LinkNode*)malloc(sizeof(LinkNode));
if (q == NULL)
return false;
q->data = x;
q->next = S->next;
S->next = q;
return true;
}
//出栈
bool Pop(LinkStack &S, ElemType &x){
if (S->next == NULL)
return false;
LinkNode* q = S->next;
x = q->data;
S->next=q->next;
free(q);
return true;
}
// 判断链栈为空
bool EmptyLinkStack(LinkStack S){
return S->next == NULL;
}
// 获取栈顶元素
bool GetTop(LinkStack S, ElemType &x){
if (S->next == NULL)
return false;
x = S->next->data;
return true;
}
int main() {
LinkStack S;
InitLiStack(S);
Push(S,2);
Push(S,1);
Push(S,3);
int x = 0;
GetTop(S,x);
printf("x = %d\n", x); // 3
Pop(S, x);
printf("出栈的元素是:%d\n", x); //3
GetTop(S,x);
printf("出栈一个元素后的栈顶元素是:%d\n", x); // 1
return 0;
}
欢迎大家在评论区交流