栈-关于顺序栈和链栈创建的相关操作

  1. 顺序栈
  2. 链栈

      ps:如果用想要尝试下使用栈来解决问题,可以看看这一篇Leetcode“有效的括号”问题

1.顺序栈

#include<iostream>
using namespace std;
#define maxSize 10
//定义顺序栈
typedef struct {
	int data[maxSize];
	int top;
}Stack;
//初始化栈
void initStack(Stack& st) {
	st.top = -1;
}
//判断栈是否为空
int isEmpty(Stack st) {

	if (st.top == -1)
	{
		return 1;
	}
	else {
		return 0;
	}
}
//进栈代码
int push(Stack &st,int x) {
	if (st.top==maxSize-1) {
		return 0;
	}
	else
	{
		++(st.top);
		st.data[st.top] = x;
		return 1;
	}
}
//出栈代码
int pop(Stack &st, int &x) {
	if (st.top == -1) {
		return 0;
	}
	else
	{
		x = st.data[st.top];
		--(st.top);
		return 1;
	}
}
//循环遍历栈,显示元素信息
void show(Stack st) {
	for (int i = 0; i < st.top+1; i++)
	{
		cout << st.data[i] <<" ";
	}
	cout << endl;
}
int main() {

	Stack st;
	int x=0;
	initStack(st);//初始化栈,设置栈顶指针为-1
	push(st, 1);//压入1
	show(st);
	push(st, 2);//压入2
	show(st);
	push(st, 3);//压入三
	show(st);
	pop(st, x);//弹出栈顶元素,并赋值给x
	show(st);
	return 0;
}

2.链栈

#include<iostream>
using namespace std;
#define maxSize 10
//定义顺序栈
typedef struct LNode {
	int data;
	struct LNode* next;
}LNode;
//初始化栈
void initStack(LNode *&list) {
	list = (LNode*)malloc(sizeof(LNode));
	list->next = NULL;
}
//判断栈是否为空
int isEmpty(LNode* list) {

	if (list->next==NULL)
	{
		return 1;
	}
	else {
		return 0;
	}
}
//进栈代码
void push(LNode*& list, int x) {
	LNode* p;
	p = (LNode*)malloc(sizeof(LNode));//初始化新栈节点
	p->next = NULL;
	p->data = x;
	p->next=list->next;//采用头插法将栈顶元素更新
	list->next = p;
	
}
//出栈代码
int pop(LNode* list, int& x) {
	LNode* p;
	if (list->next==NULL)
	{
		return 0;
	}
	p = list->next;
	x = p->data;
	list->next = p->next;
	free(p);
	return 1;

}
//循环遍历栈,显示元素信息
void show(LNode* list) {
	LNode* p;
	p = list->next;
	
	while (p!=NULL)
	{
		cout << p->data<<" ";
		p = p->next;
	}
	cout << endl;
}
int main() {

	LNode* lnode;
	int x = 1;
	initStack(lnode);
	push(lnode, 1);//压入1
	show(lnode);
	push(lnode, 2);//压入2
	show(lnode);
	push(lnode, 3);//压入3
	show(lnode);
	pop(lnode,x);//弹出栈顶元素,并赋值给x
	cout << x << endl;
	show(lnode);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值