算法与数据结构 链栈(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;
}
相关推荐
Charles Ray3 分钟前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码4 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
X同学的开始1 小时前
数据结构之二叉树遍历
数据结构
limingade2 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
jiao000015 小时前
数据结构——队列
c语言·数据结构·算法
kaneki_lh5 小时前
数据结构 - 栈
数据结构
铁匠匠匠5 小时前
从零开始学数据结构系列之第六章《排序简介》
c语言·数据结构·经验分享·笔记·学习·开源·课程设计
C-SDN花园GGbond5 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处6 小时前
C++ —— 关于vector
开发语言·c++·算法