实现堆栈的 C++ 程序

在这个程序中,我们将看到如何使用 C++ 实现堆栈。堆栈是包含元素集合的抽象数据结构。Stack 实现了 LIFO 机制,即最后被压入的元素首先被弹出。堆栈中的一些主要操作是 -

  • 推送- 这会将数据值添加到堆栈顶部。

  • Pop - 这将删除堆栈顶部的数据值

  • Peek - 这将返回堆栈的顶部数据值

下面给出了一个使用数组实现堆栈的程序。

Input: Push elements 11, 22, 33, 44, 55, 66

Output: Pop elements 66, 55, 44, 33, 22, 11

算法

push(item)

Begin

   increase the top pointer by 1

   insert item into the location top

End

pop()

Begin

   item = top element from stack

   reduce top pointer by 1

   return item

End

peek()

Begin

   item = top element from stack

   return item

End

示例代码

#include <iostream>

using namespace std;

int stack[100], n = 100, top = -1;

void push(int val) {

   if(top >= n-1)

      cout<<"Stack Overflow"<<endl;

   else {

      top++;

      stack[top] = val;

   }

}

void pop() {

   if(top <= -1)

      cout<<"Stack Underflow"<<endl;

   else {

      cout<<"弹出的元素是 "<< stack[top] <<endl;

      top--;

   }

}

void display() {

   if(top>= 0) {

      cout<<"堆栈元素是:";

      for(int i = top; i>= 0; i--)

         cout<<stack[i]<<" ";

      cout<<endl;

   } else

      cout<<"Stack is empty";

}

int main() {

   int ch, val;

   cout<<"1) Push in stack"<<endl;

   cout<<"2) Pop from stack"<<endl;

   cout<<"3) Display stack"<<endl;

   cout<<"4) Exit"<<endl;

   do {

      cout<<"输入选择: "<<endl;

      cin>>ch;

      switch(ch) {

         case 1: {

            cout<<"输入要推送的值:"<<endl;

            cin>>val;

            push(val);

            break;

         }

         case 2: {

            pop();

            break;

         }

         case 3: {

            display();

            break;

         }

         case 4: {

            cout<<"Exit"<<endl;

            break;

         }

         default: {

            cout<<"Invalid Choice"<<endl;

         }

      }

   }while(ch! = 4);

   return 0;

}

输出结果
1) Push in stack

2) Pop from stack

3) Display stack

4) Exit

输入选择: 1

输入要推送的值: 2

输入选择: 1

输入要推送的值: 6

输入选择: 1

输入要推送的值: 8

输入选择: 1

输入要推送的值: 7

输入选择: 2

弹出的元素是 7

输入选择: 3

堆栈元素是:8 6 2

输入选择: 5

Invalid Choice

输入选择: 4

Exit

以上是 实现堆栈的 C++ 程序 的全部内容, 来源链接: utcz.com/z/341423.html

回到顶部