21xrx.com
2025-03-30 23:42:15 Sunday
文章检索 我的文章 写文章
C++栈的实现代码
2023-07-09 11:12:46 深夜i     16     0
C++ stack 实现 代码

C++是一种常用的编程语言,它可以用来实现各种算法和数据结构。其中一个常见的数据结构就是栈。栈是一种后进先出(Last In First Out,LIFO)的数据结构,它的基本操作包括push(入栈)、pop(出栈)和top(获取栈顶元素)等。在C++中,我们可以使用数组或链表来实现栈。

以下是使用数组实现栈的C++代码:

#include <iostream>
#define MAX_SIZE 1000
using namespace std;
class Stack {
private:
 int stack[MAX_SIZE]; // 栈的元素,使用数组实现
 int top; // 栈顶指针
public:
 Stack() top = -1; // 初始化栈顶指针
 bool push(int val) { // 入栈操作
  if (top >= MAX_SIZE - 1) // 栈满
   return false;
  
  stack[++top] = val;
  return true;
 }
 bool pop() { // 出栈操作
  if (top == -1) // 栈空
   return false;
  
  top--;
  return true;
 }
 int topVal() { // 获取栈顶元素
  if (top == -1) 返回-1
  
  return stack[top];
 }
 bool isEmpty() return top == -1; // 判断栈空
};
int main() {
 Stack s;
 s.push(1);
 s.push(2);
 s.push(3);
 cout << s.topVal() << endl; // 输出3
 s.pop();
 cout << s.topVal() << endl; // 输出2
 s.pop();
 cout << s.topVal() << endl; // 输出1
 s.pop();
 if (s.isEmpty()) // 判断栈为空
  cout << "Stack is empty" << endl;
 
 else
  cout << "Stack is not empty" << endl;
 
 return 0;
}

在上面的代码中,我们使用数组来实现栈,声明了一个私有的stack数组用来存储栈的元素,以及一个私有的top指针用来表示栈顶元素的下标。同时,我们定义了若干公有的成员函数来实现栈的基本操作,如push、pop、topVal和isEmpty等。

在main函数中,我们先创建一个Stack对象s,然后分别入栈1、2、3,并输出栈顶元素3。接着依次出栈,并输出每次操作后的栈顶元素。最后通过isEmpty成员函数来判断栈是否为空。

总的来说,使用C++实现栈是一个比较简单的任务,只需要定义一个数组或链表,然后编写基本操作函数即可。同时,我们需要注意栈的大小和指针的引用,以及可能的异常情况,如栈满或栈空的情况。

  
  

评论区

请求出错了