栈的顺序实现和链式实现及基本操作

一,顺序栈的实现及基本操作

#include<stdio.h>
typedef int ElemType;
#define MaxSize 20  
typedef struct {   //操作受限的顺序表,多一个队头指针
	ElemType data[MaxSize];
	int top;
}SqStack;
//初始化
void initSqStack(SqStack& S) {
	S.top = -1;
}
//判断栈是否为空
bool IsFull(SqStack S) {
	if (S.top == -1)
		return true;
	else
		return false;
}
//进栈
bool Push(SqStack& S, ElemType x) {
	if (S.top == MaxSize - 1)
		return false;
	S.data[++S.top] = x;
	return true;
}
//出栈
bool  Pop(SqStack& S, ElemType& x) {
	if (S.top == -1)
		return false;
	x = S.data[S.top--];
	return true;
}
//读取栈顶元素
bool GetTop(SqStack& S, ElemType& x) {
	if (S.top == -1)
		return false;
	x = S.data[S.top];
	return false;
}
//打印栈的所有元素
void PrintfSqStack(SqStack S) {
	printf("栈的元素为:\n");
	while (S.top != -1) {
		printf("%d\n", S.data[S.top--]);
	}

}

//当top指向0表示栈为空时,top==MaxSize表表示栈满
//进栈代码为:S.data[S.top++] = x;
//出栈代码为:x = S.data[--S.top]
int main() {
	SqStack S;
	int e = 0;
	initSqStack(S);
	PrintfSqStack(S);
	Push(S, 1);
	Push(S, 2);
	Push(S, 3);
	Push(S, 4);
	Pop(S, e);
	printf("e为;%d\n", e);
	PrintfSqStack(S);
	return 0;
}

2.链栈的实现及基本操作

#include<stdio.h>
#include<malloc.h>

typedef int Elemtype;
typedef struct Stacknode {
	Elemtype data;
	struct Stacknode* next;
}*Linkstack;
//初始化链栈
void initStack(Linkstack &S) {
	S = (Linkstack)malloc(sizeof(Stacknode));
	S->next = NULL;
}
//进栈  使用头插法插入结点,正好满足栈先进后出的性质
void Push(Linkstack& S, Elemtype e) {
	Stacknode* s = (Stacknode*)malloc(sizeof(Stacknode));
	s->data = e;
	s->next = S->next;
	S->next = s;
}
//出栈
bool Pop(Linkstack& S, Elemtype& e) {
	if (S->next == NULL)
		return false;
	Stacknode* p = S->next;
	S->next = p->next;
	e = p->data;
	free(p);
	return true;
}
//读取栈顶元素
bool GetTop(Linkstack& S, Elemtype& e) {
	if (S->next == NULL)
		return false;
	e = S->next->data;
	return true;
}
//打印栈
void PrintfStack(Linkstack S) {
	printf("栈为:\n");
	Stacknode* p = S->next;
	while (p != NULL) {
		printf("%d\n", p->data);
		p = p->next;
	}
}
int main()
{
	int x = 0;
	Linkstack S;
	initStack(S);
	Push(S, 3);
	Push(S, 2);
	Push(S, 1);
	PrintfStack(S);
	Pop(S, x);
	PrintfStack(S);
	printf("x为:%d\n", x);
	GetTop(S, x);
	PrintfStack(S);
	printf("x为:%d\n", x);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值