栈的应用和实现

1 stack基本用法和实例

1.1 基本用法

  • push():向栈内压入一个元素
  • pop(): 向栈顶弹出一个元素
  • empty():判断栈是否为空,为空返回true;反之false
  • top:返回栈顶元素,但不删除成员
  • size():返回栈内元素的数量

1.2 C实现栈

C语言作为原始语言,确实很多高级的数据结构和模板泛型都不存在,但是却可以用C将它们一一实现。下面是用C实现栈。

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

struct Stack{
	int* data;
	int capacity;
	int top;
};

void init(struct Stack* ps,int k){
	ps->capacity=k;
	ps->data=(int *)malloc(sizeof(int)*k);
	ps->top=0;
}

int isFull(const struct Stack* ps){
	return ps->top==ps->capacity;
}

int isEmpty(const struct Stack* ps){
	return ps->top==0;
}

int push(struct Stack* ps,int n){
	if(isFull(ps)) return 0;
	else{
		ps->data[ps->top++]=n;
		return 1;
	}
}

int pop(struct Stack* ps,int *px){
	if(isEmpty(ps)) return 0;
	else{
		ps->top--;
		*px=ps->data[ps->top];
		return 1;
	}
}

int top(const struct Stack* ps,int *px){
	if(isEmpty(ps)) return 0;
	else{
		*px=ps->data[ps->top-1];
		return 1;
	}
}

void destroy(struct Stack* ps){
	free(ps->data);
}

int main(){
	struct Stack st;
	init(&st,5);
	push(&st,11);
	push(&st,22);
	push(&st,33);
	push(&st,44);
	push(&st,55);
	push(&st,66);
	int x;
	pop(&st,&x);
	printf("%d\n",x);
	top(&st,&x);
	printf("%d",x);
	destroy(&st);
	return 0;
}

1.3 C++栈的实例

C++的STL有stack容器,所以可以直接调用,非常方便。

#include<iostream>
#include<stack>
using namespace std;

int main()
{
    stack <int>stk;
    //入栈
    for(int i=0;i<50;i++){
        stk.push(i);
    }
    cout<<"栈的大小:"<<stk.size()<<endl;
    while(!stk.empty())
    {
        cout<<stk.top()<<endl;
        stk.pop();
    }
    cout<<"栈的大小:"<<stk.size()<<endl;
    return 0;
}

1.4 Python栈的实例

Python的list类型可以实现链表,栈和队列。如果是list类型,可以直接使用append进行入栈,使用pop进行出栈,使用len查看大小等等。

st=list()
st.append(11)
st.append(22)
st.append(33)
x=st.pop()
print(st,x)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吉大秦少游

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

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

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

打赏作者

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

抵扣说明:

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

余额充值