以下是几种栈算法的C语言实现:
- 顺序栈
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxSize 50
typedef struct {
int data[MaxSize];
int top;
}SqStack;
// 初始化栈
void InitStack(SqStack* S) {
S->top = -1;
}
// 判断栈是否为空
int IsEmptyStack(SqStack S) {
if (S.top == -1)
return 1;
else
return 0;
}
// 判断栈是否已满
int IsFullStack(SqStack S) {
if (S.top == MaxSize - 1)
return 1;
else
return 0;
}
// 入栈
int Push(SqStack* S, int x) {
if (IsFullStack(*S))
return 0;
S->top++;
S->data[S->top] = x;
return 1;
}
// 出栈
int Pop(SqStack* S, int* x) {
if (IsEmptyStack(*S))
return 0;
*x = S->data[S->top];
S->top--;
return 1;
}
- 链式栈
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct LinkNode {
int data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* top;
}LinkStack;
// 初始化栈
void InitLinkStack(LinkStack* S) {
S->top = NULL;
}
// 判断栈是否为空
int IsEmptyLinkStack(LinkStack S) {
if (S.top == NULL)
return 1;
else
return 0;
}
// 入栈
void PushLink(LinkStack* S, int x) {
LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = x;
p->next = S->top;
S->top = p;
}
// 出栈
int PopLink(LinkStack* S, int* x) {
if (IsEmptyLinkStack(*S))
return 0;
LinkNode* p = S->top;
*x = p->data;
S->top = p->next;
free(p);
return 1;
}
- 双端栈
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxSize 50
typedef struct {
int data[MaxSize];
int top1, top2;
}DoubleStack;
// 初始化栈
void InitDoubleStack(DoubleStack* S) {
S->top1 = -1;
S->top2 = MaxSize;
}
// 判断栈1是否已满
int IsFullStack1(DoubleStack S) {
if (S.top1 + 1 == S.top2)
return 1;
else
return 0;
}
// 判断栈2是否已满
int IsFullStack2(DoubleStack S) {
if (S.top2 - 1 == S.top1)
return 1;
else
return 0;
}
// 判断栈1是否为空
int IsEmptyStack1(DoubleStack S) {
if (S.top1 == -1)
return 1;
else
return 0;
}
// 判断栈2是否为空
int IsEmptyStack2(DoubleStack S) {
if (S.top2 == MaxSize)
return 1;
else
return 0;
}
// 栈1入栈
int Push1(DoubleStack* S, int x) {
if (IsFullStack1(*S))
return 0;
S->top1++;
S->data[S->top1] = x;
return 1;
}
// 栈1出栈
int Pop1(DoubleStack* S, int* x) {
if (IsEmptyStack1(*S))
return 0;
*x = S->data[S->top1];
S->top1--;
return 1;
}
// 栈2入栈
int Push2(DoubleStack* S, int x) {
if (IsFullStack2(*S))
return 0;
S->top2--;
S->data[S->top2] = x;
return 1;
}
// 栈2出栈
int Pop2(DoubleStack* S, int* x) {
if (IsEmptyStack2(*S))
return 0;
*x = S->data[S->top2];
S->top2++;
return 1;
}
希望这些实现能够帮助到您。