栈和队列

1,栈

栈的理解

在这里插入图片描述

顺序栈
#include <stdio.h>
#include <stdlib.h>
typedef struct {
	int *data;		//指针数组
	int maxlen;		//数组长度
	int top;		//指示栈顶位置;栈空:top=-1;栈满:top=maxlen-1;
}SqStack, *sqstack;

//创建顺序栈
sqstack creatStack(int len) {
	sqstack s;

	if ((s = (SqStack*)malloc(sizeof(SqStack))) == NULL) {
		printf("malloc failed !");
		return NULL;
	}
	if ((s->data = (int *)malloc(len * sizeof(int))) == NULL) {
		printf("malloc failed !");
		return NULL;
	}
	s->maxlen = len;
	s->top = -1;

	return s;
}

//栈空为1
int stack_empty(sqstack s) {
	return (s->top == -1 ? 1:0);
}

//栈满为1
int stack_full(sqstack s) {
	return (s->top == (s->maxlen - 1) ? 1:0);
}

//入栈
int stack_push(sqstack s, int value) {
	if (s->top == s->maxlen - 1) {
		printf("stack is full !");
		return -1;
	}
	s->top++;									//入栈 先把指针加一
	s->data[s->top] = value;				//再赋值
	return 1;
}

//出栈, 返回出栈的元素
int stack_pop(sqstack s) {
	if (s->top == -1)
		return 0;
	s->top--;											//原本出栈顺序为  先取出元素  再top--;
	return (s->data[s->top+1]);			//为了直接返回元素值,先top--,再top+1;
}

int main() {
	int len = 10;
	sqstack s;

	s = creatStack(len);
	stack_push(s, 1);
	stack_push(s, 2);
	stack_push(s, 4);
	stack_push(s, 6);
	while(!stack_empty(s))
		printf("出栈元素 %d\n", stack_pop(s));
	return 0;
}

链栈
#include <stdio.h>
#include <stdlib.h>

typedef int Elemtype;
//链栈的结构体
typedef struct node {
	Elemtype data;
	struct node* next;
}LinkStack, *linkstack;

//初始化
linkstack stack_init() {
	linkstack s;
	s = (LinkStack *)malloc(sizeof(LinkStack));
	s = NULL;
	return s;
}

//销毁栈
void stack_destroy(linkstack &s) {
	linkstack pre = s, p = pre->next;		//pre为头结点,p为第一个数据的结点
	if (pre == NULL)		
		return;
	while (p!=NULL)
	{
		free(pre);
		pre = p; 
		p = p->next;
	}
	free(pre);
}

//入栈
void stack_push(linkstack &s, Elemtype x) {
	linkstack p;
	p = (LinkStack *)malloc(sizeof(LinkStack));
	p->data = x;
	p->next = s;			//在链栈的最前端头结点加入数据
	s = p;					//加入的结点成为头结点
 
}

//出栈
int stack_pop(linkstack &s, Elemtype &x) {		//s,x要加引用,回代参数
	linkstack p;

	if (s == NULL)
		return 0;

	p = s;			//头结点给新的结点p
	x = p->data;	//取出头结点的数据
	s = p->next;	//头结点后移
	free(p);		//释放原头结点
}

//判断栈是否为空,栈空为1
int stack_empty(linkstack s) {
	if (s == NULL)
		return 1;
	else
		return 0;
}

int main() {
	Elemtype e;
	linkstack s;
	e = 0;
	s = stack_init();
	stack_push(s, 1);
	stack_push(s, 3);
	stack_push(s, 5);
	stack_push(s, 7);

	while (!stack_empty(s))
	{
		stack_pop(s,e);
		printf("pop: %d\n", e);
	}

	return 1;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大头熊在学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值