21xrx.com
2024-06-03 04:12:44 Monday
登录
文章检索 我的文章 写文章
C++ 栈源码
2023-07-05 04:56:03 深夜i     --     --
C++ 源码

C++ 栈是一种常见的数据结构,它可以用于存储和管理数据。在 C++ 中,可以通过类或数组实现栈。类实现的栈通常包含 Push、Pop、IsEmpty 和 IsFull 等方法,而数组实现的栈则可以使用下标来访问栈内元素。

下面是一个简单的 C++ 栈实现代码:


#include<iostream>

using namespace std;

const int MAXSIZE = 100;

class Stack {

private:

  int top;

  int stack[MAXSIZE];

public:

  Stack()

    top = -1;

  

  

  bool IsEmpty() {

    if (top == -1)

      return true;

    

    else

      return false;

    

  }

  

  bool IsFull() {

    if (top == MAXSIZE - 1)

      return true;

    

    else

      return false;

    

  }

  

  void Push(int value) {

    if (IsFull())

      cout << "The stack is full." << endl;

    

    else {

      top++;

      stack[top] = value;

    }

  }

  

  void Pop() {

    if (IsEmpty())

      cout << "The stack is empty." << endl;

    

    else

      top--;

    

  }

  

  int Top() {

    if (IsEmpty())

      cout << "The stack is empty." << endl;

      return -1;

    

    else {

      return stack[top];

    }

  }

};

int main() {

  Stack s;

  s.Push(1);

  s.Push(2);

  s.Push(3);

  s.Pop();

  cout << s.Top() << endl;

  return 0;

}

在上面的代码中,我们通过定义一个 Stack 类来实现一个简单的栈。其中,通过私有变量来存储栈的元素,然后通过公共的 Push、Pop、IsEmpty 和 IsFull 方法来对栈进行操作。同时,在主函数中,我们也可以进行栈的调用和使用,如 Push 三个元素 1、2、3 到栈中,然后 Pop 出一个元素,最后输出栈顶元素。

综上所述,C++ 栈是一种重要的数据结构,在有些算法和程序实现中极为关键。如果您对栈的理解和使用有所限制,不妨通过阅读和使用 C++ 栈源码来加深理解并提升能力。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复