算法与数据结构 链栈(C++)

2.随机产生10个100以内的整数建立一个链栈,从栈顶到栈底依次显示栈内元素;从键盘输入出栈元素个数 n (1<= n <=10),将 n 个元素依次出栈并显示出栈元素,再显示此时栈顶元素;

cpp 复制代码
#include <iostream>  
#include <cstdlib>  
#include <ctime>  
using namespace std;
template <typename DataType>
class Node {
public:
    DataType data;
    Node<DataType>* next;
};
template <typename DataType>
class LinkStack {
private:
    Node<DataType>* top;
public:
    LinkStack() : top(nullptr) {} // 构造函数初始化栈顶指针  
    void Push(DataType x);
    DataType Pop();
    void GenerateAndPushRandomNumbers(); // 生成随机数并压入链栈  
    void DisplayStack(); // 显示链栈元素  
    void PopAndDisplay(int n); // 出栈n个元素并显示  
    void DisplayTop(); // 显示栈顶元素  
};
template <typename DataType>
void LinkStack<DataType>::Push(DataType x) {
    Node<DataType>* newNode = new Node<DataType>;
    newNode->data = x;
    newNode->next = top;
    top = newNode;
}
template <typename DataType>
DataType LinkStack<DataType>::Pop() {
    if (top == nullptr) {
        throw "下溢";
    }
    Node<DataType>* temp = top;
    DataType x = top->data;
    top = top->next;
    delete temp;
    return x;
}
template <typename DataType>
void LinkStack<DataType>::GenerateAndPushRandomNumbers() {
    srand(time(nullptr)); // 初始化随机数种子  
    for (int i = 0; i < 10; ++i) {
        int randomNumber = rand() % 100; // 生成0到99的随机数  
        Push(randomNumber);
    }
}
template <typename DataType>
void LinkStack<DataType>::DisplayStack() {
    Node<DataType>* current = top;
    cout << "Elements in the stack (from top to bottom): ";
    while (current != nullptr) {
        cout << current->data << " ";
        current = current->next;
    }
    cout << endl;
}
template <typename DataType>
void LinkStack<DataType>::PopAndDisplay(int n) {
    for (int i = 0; i < n; ++i) {
        
            DataType poppedElement = Pop();
            cout << "Popped element: " << poppedElement << endl;
    }
}
template <typename DataType>
void LinkStack<DataType>::DisplayTop() {
    if (top != nullptr) {
        cout << "Top element: " << top->data << endl;
    }
    else {
        cout << "Stack is empty." << endl;
    }
}
int main() {
    LinkStack<int> stack;
    stack.GenerateAndPushRandomNumbers(); // 生成随机数并压入链栈  
    stack.DisplayStack(); // 显示栈内元素  
    int n;
    cout << "Enter the number of elements to pop (1-10): ";
    cin >> n;
    stack.PopAndDisplay(n); // 出栈并显示元素  
    stack.DisplayTop(); // 显示栈顶元素  
    return 0;
}
相关推荐
努力学习的小廉几秒前
我爱学算法之—— 递归回溯综合(二)
开发语言·算法
sheji52612 分钟前
JSP基于信息安全的读书网站79f9s--程序+源码+数据库+调试部署+开发环境
java·开发语言·数据库·算法
2301_763472462 分钟前
C++网络编程(Boost.Asio)
开发语言·c++·算法
依依yyy7 分钟前
沪深300指数收益率波动性分析与预测——基于ARMA-GARCH模型
人工智能·算法·机器学习
轩情吖29 分钟前
Qt的窗口
开发语言·c++·qt·窗口·工具栏·桌面级开发
L1869245478239 分钟前
无外设条件下的自动找眼V2
c++
hcnaisd240 分钟前
深入理解C++内存模型
开发语言·c++·算法
李老师讲编程1 小时前
C++信息学奥赛练习题-杨辉三角
数据结构·c++·算法·青少年编程·信息学奥赛
zxsz_com_cn1 小时前
设备预测性维护算法核心功能有哪些?六大模块拆解智能运维的“技术骨架”
运维·算法
期末考复习中,蓝桥杯都没时间学了1 小时前
力扣刷题13
数据结构·算法·leetcode