链栈

链栈与栈的逻辑结构相同,只不过存储结构不同。

链栈的表头指针为栈顶指针。

链栈的优点是不用指定内存。只要操作系统没用光,就能一直push。

按理来说应该会有一个表示这个栈长度的私有量,但是因为我懒,所以没弄

示意图

 这里仅给出链栈的pop与push操作

#include <iostream>

struct Node
{
    int data;
    Node *next;
};

class LinkStack
{
private:
    Node *head;

public:
    LinkStack()
    {//构造函数
        head = new Node;
        head->next = nullptr;
    }
    bool push(int a);
    bool pop(int *a);
};
bool LinkStack::push(int a)
{//压栈
    Node *newNode;
    try//异常处理
    {
        newNode = new Node();
    }
    catch (const std::bad_alloc &e)
    {
        return false;
    }

    newNode->data = a;
    newNode->next = this->head->next;
    this->head->next = newNode;
    return true;
}

bool LinkStack::pop(int *a)
{//出栈
    Node *node = this->head->next;
    if (node == nullptr)
    {
        return false;
    }
    *a = node->data;
    this->head->next = node->next;
    delete node;
    return true;
}

int main()
{
    LinkStack a;
    int b;
    a.pop(&b);
    a.push(6);
}

  

 

posted @ 2022-03-11 17:05  帝皇の惊  阅读(50)  评论(0)    收藏  举报