C/C++ Stack (栈)

简介


数组模拟栈


在数组上实现时,栈底位置可以设置在数组的任一个端点,而栈顶是随着插入和删除而变化的,可以用一个整形变量 top 存放栈顶的指针,数据入栈或出栈时使整形变量 top 分别加1或减1。

Code

注意:部分题目 top-- 之前必须判断 top 是否大于等于 0,避免数组越界访问

#include <stdio.h>

int main()
{
	int stack[10086],top=0;
	
	stack[top++]=5; //入栈 
	stack[top++]=10;
	
	printf("栈中有 %d 个元素\n",top);
	printf("栈顶元素为 %d\n\n",stack[top-1]);
	
	top--; //出栈 
	printf("栈中有 %d 个元素\n",top);
	printf("栈顶元素为 %d\n\n",stack[top-1]);
	
	if(top>0)printf("栈不是空的!\n");
	else  printf("栈是空的!\n");
	
	top--;
	if(top>0)printf("栈不是空的!\n");
	else  printf("栈是空的!\n");
	
	return 0;
}

在这里插入图片描述

C++ STL 中的栈


头文件 #include <stack>
需要使用 std 命名空间 using namespace std;

  • 初始化 (定义) 栈 stack<int> sta;
  • 入栈 sta.push(x)
  • 出栈 sta.pop()
  • 判断栈是否为空 sta.empty()
  • 获取栈中元素数量 sta.size()
  • 取得栈顶元素 sta.top()

Code

注意:部分题目 sta.pop() 之前必须判断 sta 是否为空
对空栈进行出栈操作会产生 Runtime Error

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

int main()
{
	stack<int> sta;
	
	sta.push(5); //入栈 
	sta.push(10);
	
	cout<<"栈中有 "<<sta.size()<<" 个元素"<<endl;
	cout<<"栈顶元素为 "<<sta.top()<<endl<<endl;
	
	sta.pop(); //出栈 
	cout<<"栈中有 "<<sta.size()<<" 个元素"<<endl;
	cout<<"栈顶元素为 "<<sta.top()<<endl<<endl;
	
	if(sta.empty())cout<<"栈是空的!"<<endl;
	else  printf("栈不是空的!\n");
	
	sta.pop();
	if(sta.empty())cout<<"栈是空的!"<<endl;
	else  printf("栈不是空的!\n");
	
	return 0;
}

在这里插入图片描述

发布了32 篇原创文章 · 获赞 104 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/csg999/article/details/103889495
今日推荐