涉及知识点:内存管理、结构体定义、基本数据结构
要求:编写一个程序模拟堆栈,要求能够模拟入栈、出栈、返回栈顶元素等基本操作。栈中元素可用整数代替。不能使用C++模板库预定义的类型。程序运行中可输入多组入栈、出栈操作,每次操作后展示栈中元素。
思路:
一,定义一个结构体Node为栈的节点,里面包含节点内的数据和指向下一个节点的指针
二,定义一个堆栈类,包含栈顶节点,和出入栈的函数
三,写一个简单的系统,实现模拟用户出入栈操作;
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
void showMenu()
{
cout << "*************************" << endl;
cout << "*****1、入栈*************" << endl;
cout << "*****2、出栈*************" << endl;
cout << "*****3、返回栈顶*********" << endl;
cout << "*****4、打印栈中元素*****" << endl;
cout << "*****5、退出系统*********" << endl;
cout << "*************************" << endl;
}
struct Node // 栈的节点
{
int data;
Node *next; // 指向下一个节点
};
class Stack // 定义堆栈类
{
private:
Node *top; // 栈顶节点
public:
Stack() // 初始化
{
top = nullptr;
}
// 入栈
void push(int value)
{
Node *newNode = new Node;
newNode->data = value;
newNode->next = top;
top = newNode; // 指向新节点,使新节点成为栈顶
}
// 出栈
void pop()
{
if (top == nullptr)
{
return;
}
top = top->next;
}
// 返回栈顶元素
void peek()
{
int temp;
if (top == nullptr)
{
cout << "栈内为空!" << endl;
}
else
{
temp = top->data;
cout << "栈顶元素为: " << endl;
cout << temp << endl;
}
}
// 打印栈中元素
void printStack()
{
Node *current = top;
cout << "栈内元素有: " << endl;
while (current != nullptr)
{
cout << current->data << " ";
current = current->next;
}
}
};
int main()
{
int n;
int temp[10000];
int select;
Stack stack;
while (true)
{
showMenu();
cin >> select;
switch (select)
{
case 1: // 入栈
cout << "请输入要入栈的值的个数: " << endl;
cin >> n;
cout << "请输入要入栈的值: " << endl;
for (int i = 0; i < n; i++)
{
cin >> temp[i];
}
for (int i = 0; i < n; i++)
{
stack.push(temp[i]);
}
stack.printStack();
cout << endl;
break;
case 2: // 出栈
stack.pop();
stack.printStack();
cout << endl;
break;
case 3: // 返回栈顶元素
stack.peek();
break;
case 4: // 打印栈中元素
stack.printStack();
cout << endl;
break;
case 5: // 退出
cout << "已退出" << endl;
return 0;
break;
}
system("pause");
system("cls");
}
}
仅供参考