其他分享
首页 > 其他分享> > 链栈

链栈

作者:互联网

老师:青岛大学-王卓

 

 

#include <iostream>
using namespace std;


typedef struct StackNode
{
    int data;
    struct StackNode* next;
}StackNode, *LinkStack;


//链栈的初始化
void initLinkStack(LinkStack& s)
{
    s = nullptr;
}

//判断链栈是否为空
bool isEmpty(LinkStack s)
{
    if (s == nullptr) return true;
    else return false;
}

//链栈的入栈
bool push(LinkStack& s, int value)
{
    StackNode* node = new StackNode;
    node->data = value;
    node->next = s;
    s = node;

    return true;
}

//链栈的出栈
bool pop(LinkStack& s, int value)
{
    if (s == nullptr)return false;   //栈空

    StackNode* p = s;   //1.保存要删除的结点(栈顶指针)
    value = s->data;   //2.取值返回
    s = s->next;   //3.栈顶下移
    delete p;

    return true;
}

//取栈顶元素
int top(LinkStack& s)
{
    if (s) return s->data;
}

void main()
{
    LinkStack s;
    initLinkStack(s);

    cout << "链栈" << (isEmpty(s) ? "为空" : "不为空") << endl;

    cout << "链栈入栈:" << endl;
    for (int i = 0; i < 10; i++)
        push(s, i);
    cout << "链栈" << (isEmpty(s) ? "为空" : "不为空") << endl;

    cout << "栈顶元素:" << top(s) << endl;
}

 

标签:node,LinkStack,return,int,链栈,StackNode
来源: https://www.cnblogs.com/tingtaishou/p/14946400.html