21xrx.com
2025-04-28 02:31:36 Monday
文章检索 我的文章 写文章
C++栈的实现代码
2023-07-06 17:55:21 深夜i     2116     0
C++ 实现 代码

C++栈作为一种常见的数据结构,我们在编程中经常使用。他是一种具有数据结构特性的容器,我们可以将数据放入其中,也可以从其中取出数据。关于C++栈的实现,我们有两种方式:使用stl库中的stack,或是自己手写栈的实现代码。

使用stack:

如果我们使用stl库中的stack,我们需要包含头文件 ,然后通过下面的代码来定义一个栈对象。

#include <stack>
using namespace std;
stack<T> s; // 声明一个空栈

这里的T代表数据类型,可以是int、float、char等类型。

然后我们可以通过push()来将数据推入栈中,通过pop()来弹出栈顶元素,通过top()来获取栈顶元素,通过empty()来判断栈是否为空,通过size()来获取栈的大小。

下面是一个使用stack的代码示例:

#include <iostream>
#include <stack>
using namespace std;
int main()
{
  stack<int> s; // 声明一个空栈
  s.push(10); // 将10压入栈
  s.push(20); // 将20压入栈
  s.push(30); // 将30压入栈
  cout << "栈顶元素:" << s.top() << endl; // 输出:栈顶元素:30
  s.pop(); // 弹出栈顶元素
  cout << "栈顶元素:" << s.top() << endl; // 输出:栈顶元素:20
  while (!s.empty()) // 当栈不为空时,循环输出栈元素
  {
    cout << s.top() << endl;
    s.pop(); // 弹出栈顶元素
  }
  return 0;
}

手写栈的实现代码:

如果我们希望自己手写栈的实现代码,下面是一份简单的代码示例:

#include <iostream>
using namespace std;
#define MAX_SIZE 100 // 栈的最大容量
class Stack
{
public:
  Stack() : top(-1) {}
  void push(int val);
  void pop();
  int get_top();
  bool is_empty();
private:
  int data[MAX_SIZE];
  int top; // 栈顶指针
};
void Stack::push(int val)
{
  if (top >= MAX_SIZE - 1) // 判断栈是否已满
  无法插入元素!" << endl;
    return;
  
  top++;
  data[top] = val;
}
void Stack::pop()
{
  if (top < 0) // 判断栈是否为空
  
    cout << "栈为空
  top--;
}
int Stack::get_top()
{
  if (top < 0) // 判断栈是否为空
  
    cout << "栈为空!" << endl;
    return -1;
  
  return data[top];
}
bool Stack::is_empty()
  return top < 0;
int main()
{
  Stack s;
  s.push(10);
  s.push(20);
  s.push(30);
  cout << "栈顶元素:" << s.get_top() << endl; // 输出:栈顶元素:30
  s.pop();
  cout << "栈顶元素:" << s.get_top() << endl; // 输出:栈顶元素:20
  while (!s.is_empty()) // 当栈不为空时,循环输出栈元素
  {
    cout << s.get_top() << endl;
    s.pop();
  }
  return 0;
}

这份代码使用类来封装栈,包括push()、pop()、get_top()、is_empty()等方法来实现栈元素的添加、删除、获取等功能。在使用手写栈时,需要注意栈的大小MAX_SIZE,避免出现栈溢出的情况。

总结:

无论是使用stl库中的stack,还是手写栈的实现代码,我们在实际编程中都可以选择合适的方式来满足要求。当我们需要方便快捷地使用栈时,使用stl库中的stack是最佳选择。而当我们需要了解栈的实现原理及其应用时,手写栈的实现代码是不可或缺的。

  
  

评论区

请求出错了