stack链式C++

#include <iostream>
using namespace std;

typedef struct _node{
    int data;
    struct _node* next;
    _node(int e ,struct _node* p = nullptr){
        data = e;
        next = p;   
    }
}node;

class stack{
public:
    stack():m_start(new node(-1,nullptr)){}
    ~stack(){
        while(m_start->next != nullptr){
            node* pdel = m_start;
            m_start = m_start->next;
            delete pdel;
        }
        m_start = nullptr;
    }

    void push(int e);
    void pop();
    int  top();
    bool isEmpty(); 
private:
    node* m_start;
};
//头插法
void stack::push(int e){
    node* pnew = new node(e,nullptr);
    pnew->next = m_start->next;
    m_start->next = pnew;
}

void stack::pop(){
    if(m_start->next != nullptr){
        node* pdel = m_start->next;
        m_start->next = m_start->next->next;
        delete pdel;    
    }else{
        cout << "stack is empty.\n";
    }
}

int  stack::top(){
    if(m_start->next != nullptr){
        return m_start->next->data;
    }else{
        cout << "stack is empty.\n";
        exit(1);
    }
}

bool stack::isEmpty(){
    return m_start->next == nullptr;
}


int main(){
    stack s;
    s.push(1);
    s.push(2);
    s.push(3);
    while(!s.isEmpty()){
        cout << s.top() << ends;
        s.pop();    
    }
    cout << endl;
    s.pop();

    return 0;
}

这里写图片描述

C语言中的链式栈(linked stack)是一种基于链表实现的栈,它可以动态地增加或删除元素,并且不用考虑栈的大小限制。 链式栈的实现需要定义一个结构体,该结构体包含一个指向栈顶的指针和链表节点的个数。 ```c struct node { int data; struct node* next; }; typedef struct { struct node* top; int size; } stack; ``` 在定义结构体之后,我们需要实现以下几个常见的操作: 1. 初始化栈 ```c void init_stack(stack* s) { s->top = NULL; s->size = 0; } ``` 2. 判断栈是否为空 ```c int is_empty(stack* s) { return s->size == 0; } ``` 3. 入栈 ```c void push(stack* s, int data) { struct node* new_node = (struct node*)malloc(sizeof(struct node)); new_node->data = data; new_node->next = s->top; s->top = new_node; s->size++; } ``` 4. 出栈 ```c int pop(stack* s) { if (is_empty(s)) { printf("Stack is empty.\n"); return -1; } int data = s->top->data; struct node* temp = s->top; s->top = s->top->next; free(temp); s->size--; return data; } ``` 5. 获取栈顶元素 ```c int top(stack* s) { if (is_empty(s)) { printf("Stack is empty.\n"); return -1; } return s->top->data; } ``` 6. 清空栈 ```c void clear(stack* s) { while (!is_empty(s)) { pop(s); } } ``` 这些操作都是基于链表的操作,因此链式栈可以动态地增加或删除元素,并且不用考虑栈的大小限制。但是,由于链式栈的实现需要动态分配内存,因此它的空间复杂度比数组栈要高。在使用链式栈时,需要注意内存泄漏的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值