算法与数据结构 链栈(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;
}
相关推荐
mit6.82414 分钟前
前后缀分解
算法
独自破碎E1 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白1 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
Larry_Yanan3 小时前
QML学习笔记(四十二)QML的MessageDialog
c++·笔记·qt·学习·ui
寂静山林3 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway3 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
R-G-B4 小时前
【35】MFC入门到精通——MFC运行 不显示对话框 MFC界面不显示
c++·mfc·mfc运行 不显界面·mfc界面不显示
Madison-No74 小时前
【C++】探秘vector的底层实现
java·c++·算法
晚风残4 小时前
【C++ Primer】第十二章:动态内存管理
开发语言·c++·c++ primer
Swift社区4 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh