链栈——不带头节点

1、代码

#include <iostream>
#include <cstdlib>

#define MaxSize 10

typedef int ElemType;

typedef struct LNode {
    ElemType data;
    struct LNode* next;
} LNode, * LinkStack;

int Length(LinkStack& S) {
    int i = 0;
    LNode* p = S;
    while (p != NULL) {
        p = p->next;
        i++;
    }
    return i;
}

void InitLinkStack(LinkStack& S) {
    S = NULL;
}

bool IsFullLinkStack(LinkStack& S) {
    if (Length(S) == MaxSize)
        return true;
    return false;
}

bool IsEmptyLinkStack(LinkStack& S) {
    if (S == NULL)
        return true;
    return false;
}

bool Push(LinkStack& S, ElemType x) {
    if (IsFullLinkStack(S))
        return false;
    LNode* p = (LNode*)malloc(sizeof(LNode));
    if (p == NULL)
        return false;
    p->data = x;
    p->next = S;
    S = p;
    return true;
}

bool Pop(LinkStack& S, ElemType& x) {
    if (IsEmptyLinkStack(S))
        return false;
    LNode* p = S;
    x = p->data;
    S = p->next;
    free(p);
    return true;
}

bool GetElem(LinkStack& S, ElemType& x) {
    if (IsEmptyLinkStack(S))
        return false;
    x = S->data;
    return true;
}

void Destroy(LinkStack& S) {
    ElemType x;
    while (!IsEmptyLinkStack(S))
        Pop(S, x);
}

int main() {
    LinkStack stack;
    InitLinkStack(stack);

    // Push elements into stack
    ElemType a = 1;
    ElemType b = 2;
    ElemType c = 3;
    ElemType d = 4;
    ElemType e = 5;
    
    ElemType j = 11;
    ElemType f = 22;
    ElemType g = 33;
    ElemType h = 44;
    ElemType i = 55;
    
    Push(stack, a);
    Push(stack, b);
    Push(stack, c);
    Push(stack, d);
    Push(stack, e);
      
    Push(stack, j);
    Push(stack, f);
    Push(stack, g);
    Push(stack, h);
    Push(stack, i);
    
    int stackLength = Length(stack);
    std::cout << "Stack Length: " << stackLength << std::endl;

    // Check if the stack is empty
    bool isEmpty = IsEmptyLinkStack(stack);
    if (isEmpty) {
        std::cout << "Stack is empty" << std::endl;
    } else {
        std::cout << "Stack is not empty" << std::endl;
    }

    // Check if the stack is full
    bool isFull = IsFullLinkStack(stack);
    if (isFull) {
        std::cout << "Stack is full" << std::endl;
    } else {
        std::cout << "Stack is not full" << std::endl;
    }

    // Pop and print elements from stack
    ElemType x;
    while (Pop(stack, x)) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    Destroy(stack);

    return 0;
}

2、运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值