栈的链式存储_笔记

这里写图片描述

只允许容器往一个方向进出,先进后出为栈容器

.h

//链式栈的节点
typedef struct LINKNODE
{
    struct LINKNODE*next;
}LinkNode;

//链式栈
typedef struct LINKSTACK
{
    LinkNode head;
    int size;

}LinkStack;


class linkstack
{
public:
    linkstack();
    ~linkstack();
public:
    LinkStack* Stack;

public:
    //入栈
    void push_back(LinkStack* stack,LinkNode* data);
    //出栈
    void pop_back(LinkStack* stack);
    //返回栈顶元素
    LinkNode* Top_LinkStack(LinkStack* stack);
    //返回栈元素的个数
    int Size_LinkStack(LinkStack* stack);
    //清空栈
    void Clear_LinkStack(LinkStack* stack);


};

.cpp

linkstack::linkstack()
{
    Stack = new LinkStack;

    Stack->head.next = NULL;
    Stack->size = 0;
}

linkstack::~linkstack()
{
    if (Stack == NULL)
    {
        return;
    }

    delete Stack;


}

//入栈
void linkstack::push_back(LinkStack* stack, LinkNode* data)
{
    if (stack == NULL || data == NULL)
    {
        return;
    }

    data->next = stack->head.next;
    stack->head.next = data;
    stack->size++;
}

//出栈
void linkstack::pop_back(LinkStack* stack)
{
    if (stack == NULL || stack->size == 0)
    {
        return;
    }

    LinkNode* pNext = stack->head.next;
    stack->head.next = pNext->next;

    stack->size--;
}

//返回栈顶元素
LinkNode* linkstack::Top_LinkStack(LinkStack* stack)
{
    if (stack == NULL || stack->size == 0)
    {
        return NULL;
    }

    return stack->head.next;
}

//返回栈元素的个数
int linkstack::Size_LinkStack(LinkStack* stack)
{
    if (stack == NULL )
    {
        return -1;
    }

    return stack->size;
}

//清空栈
void linkstack::Clear_LinkStack(LinkStack* stack)
{
    if (stack == NULL || stack->size == 0)
    {
        return;
    }

    stack->head.next = NULL;
    stack->size = 0;
}

main.cpp


typedef struct PERSON
{
    LinkNode node;
    char name[64];
    int age;
}Person;


int main()
{
    linkstack* l = new linkstack();

    //创建数据
    Person p1, p2, p3, p4, p5;
    strcpy(p1.name, "p1");
    strcpy(p2.name, "p2");
    strcpy(p3.name, "p3");
    strcpy(p4.name, "p4");
    strcpy(p5.name, "p5");

    p1.age = 10;
    p2.age = 20;
    p3.age = 30;
    p4.age = 40;
    p5.age = 50;

    //入栈
    l->push_back(l->Stack, (LinkNode*)&p1);
    l->push_back(l->Stack, (LinkNode*)&p2);
    l->push_back(l->Stack, (LinkNode*)&p3);
    l->push_back(l->Stack, (LinkNode*)&p4);
    l->push_back(l->Stack, (LinkNode*)&p5);

    //输出
    while (l->Size_LinkStack(l->Stack) >0)
    {
        //取出栈顶元素
        Person* p = (Person*)l->Top_LinkStack(l->Stack);

        cout << "Name:" << p->name << " ";
        cout << "Age:" << p->name << " ";
        cout << endl;

        //弹出栈顶元素
        l->pop_back(l->Stack);

    }

    delete l;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值