算法与数据结构 链栈(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;
}
相关推荐
@Aurora.8 分钟前
数据结构手撕--【二叉树】
数据结构·算法
悲伤小伞8 分钟前
C++_数据结构_详解红黑树
数据结构
victd15 分钟前
什么是AutoRec?
算法
陈壮实的搬砖日记16 分钟前
抛硬币背后的秘密-通俗玩转二项分布
算法
前端 贾公子18 分钟前
力扣 83 . 删除排序链表中的重复元素:深入解析与实现
数据结构·算法
Y1nhl20 分钟前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
_w_z_j_30 分钟前
C++----模拟实现string
开发语言·c++
特立独行的猫a30 分钟前
redis客户端库redis++在嵌入式Linux下的交叉编译及使用
linux·数据库·c++·redis·redis客户端库
张槊哲32 分钟前
const(C++)
开发语言·c++
oioihoii37 分钟前
C++23 中 constexpr 的重要改动
c++·算法·c++23