线性表的链式存储

/*
如果将链表的尾部作为栈顶,那么每次进行入栈和出栈操作都需要遍历链表找到尾部,这样的时间复杂度是 O(n),其中 n 是链表的长度。
而将链表的头部作为栈顶,则可以在常量时间内完成插入和删除操作,因为只需调整链表头的指针即可,时间复杂度为 O(1)。
*/
//与顺序表的链式存储不同,其头结点表示top,不存储任何值
#include<iostream>
using namespace std;
template <typename T>
class Node{
public:
    T data;
    Node* next;
    Node(){
        next=nullptr;
    }
};

template <typename T>
class chain_stack
{
private:
    Node<T>* top;
public:
    chain_stack(){
        top=nullptr;//表明了头节点的初始状态是空的,而不是指向任何实际节点
    }
    bool isEmpty(){//判断栈是否为空
        return (top->next==nullptr)
    }
    //入栈
    bool push(T elem){
        Node<T>* temp=new Node<T>();
        temp->data=elem;
        temp->next=top->next;
        top->next=temp;
        return true;
    }
    //出栈
    T pop(){
        if (isEmpty())
        {
            throw underflow_error("Stack underflow");
        }
        Node<T>* temp=top->next;
        T elem=temp->data;
        top->next=temp->next;
        delete temp;
        return elem;

    }
};

  

posted @ 2023-11-19 15:09  44556677  阅读(5)  评论(0)    收藏  举报