算法与数据结构 链栈(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;
}
相关推荐
吴声子夜歌18 分钟前
OpenCV——Mat类及常用数据结构
数据结构·opencv·webpack
笑口常开xpr1 小时前
数 据 结 构 进 阶:哨 兵 位 的 头 结 点 如 何 简 化 链 表 操 作
数据结构·链表·哨兵位的头节点
BUG收容所所长1 小时前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
愚润求学1 小时前
【C++】类型转换
开发语言·c++
XRZaaa1 小时前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪2 小时前
数据结构测试模拟题(4)
数据结构·c++·算法
智驱力人工智能2 小时前
智慧零售管理中的客流统计与属性分析
人工智能·算法·边缘计算·零售·智慧零售·聚众识别·人员计数
csdnzzt2 小时前
从内存角度透视现代C++关键特性
c++
jie188945758662 小时前
C++ 中的 const 知识点详解,c++和c语言区别
java·c语言·c++
明月*清风2 小时前
c++ —— 内存管理
开发语言·c++