栈的链式存储结构实现

简介: 栈的链式存储结构实现

栈的链式存储结构实现

(1) 用随机函数生成10个3位整数(100~999),把这些整数应用入栈操作存于堆栈中,在入栈接口处设置断点①,按“F5”启动调试,按“F10”逐句执行,直到数据全部入栈。程序暂停时观察栈顶数据和栈顶位置;

(2) 应用出栈操作输出堆栈的内容,在出栈接口处设置断点②,按“F5”启动调试,按“F10”逐句执行,直到所有数据完全出栈,程序暂停时观察栈顶数据和栈顶位置的变化。

#include <iostream>
#include<math.h>
#include<ctime>
using namespace std;
template<class T>class Stack
{
private:
    struct Node
    {
        T data;
        Node* next;
    };
    Node* head;
    Node* p;
    int length;
public:
    Stack()
    {
        head = NULL;
        length = 0;
    }
    void push(T n)//入栈
    {
        Node* q = new Node;
        q->data = n;
        if (head == NULL)
        {
            q->next = head;
            head = q;
            p = q;
        }
        else
        {
            q->next = p;
            p = q;
        }
        cout << q->data << endl;
        length++;
    }
    T pop()//出栈并且将出栈的元素返回
    {
        if (length <= 0)
        {
            abort();
        }
        Node* q;
        T data;
        q = p;
        data = p->data;
        p = p->next;
        delete(q);
        length--;
        return data;
    }
    bool isEmpty()//判断栈是不是空的
    {
        if (length == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};
int main()
{
    Stack<int> s;
    time_t t1;
    srand((unsigned int)time(&t1));
    for (int i = 0; i < 10; i++)
    {
        int a = rand() % 900 + 100;
        s.push(a);
    }
    while (!s.isEmpty())
    {
        cout << s.pop()<<" 已出栈"<< endl;
    }
    return 0;
}
相关文章
|
5天前
|
存储 Java 容器
深入浅出 栈和队列(附加循环队列、双端队列)
深入浅出 栈和队列(附加循环队列、双端队列)
|
2天前
|
算法 编译器 Python
栈的最后表演:逆波兰表达式求值
栈的最后表演:逆波兰表达式求值
|
6天前
<数据结构>栈和队列. 顺序表实现栈,单链表实现队列.
<数据结构>栈和队列. 顺序表实现栈,单链表实现队列
16 3
TU^
|
10天前
|
存储 调度 索引
数据结构~~栈和队列
在计算机科学中,数据结构是构建高效程序的基础。栈和队列是两种重要且常用的线性数据结构,它们在解决各种问题中发挥着关键作用。
TU^
22 1
|
6天前
|
存储 测试技术 计算机视觉
栈和队列经典练习题
栈和队列经典练习题
16 3
|
6天前
|
C++
数据结构深入理解--栈
数据结构深入理解--栈
15 0
|
6天前
|
Java 索引
Java数据结构——栈
Java数据结构——栈
18 1
|
9天前
|
缓存 Java 编译器
JavaSE精选-栈和队列
JavaSE精选-栈和队列
16 1