堆栈 | 数组实现 & 链表实现 | C语言

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一、数组实现

在这里插入图片描述

#include "stacking.h"

typedef int Position;
typedef struct SNode *Stack;
struct SNode {
    ElementType *Data;  // 存储元素的数组
    Position Top;       // 栈顶指针
    int MaxSize;        // 堆栈最大容量
};

Stack CreateStack(int MaxSize)
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    S->Top = -1;
    S->MaxSize = MaxSize;
    return S;
}

bool IsFull(Stack S)
{
    return (S->Top == S->MaxSize-1);
}

bool Push(Stack PtrS, ElementType item)
{
    if (PtrS->Top == MaxSize-1) {
        printf("堆栈满");
        return false;
    }
    else {
        PtrS->Data[++(PtrS->Top)] = item;
        return true;
    }
}

bool IsEmpty(Stack S)
{
    return (S->Top == -1);
}

ElementType Pop(Stack PtrS)
{
    if ( PtrS->Top == -1 ) {
        printf("堆栈空");
        return ERROR;         // ERROR是ElementType的特殊值,标志错误
    } else
        return (PtrS->Data[(PtrS->Top)--]);
}

二、链表实现

在这里插入图片描述

#include <stdio.h>

typedef struct SNode *Stack;
struct SNode{
    ElementType Data;
    struct SNode *Next;
}

Stack CreateStack()
{   // 构建一个堆栈的头结点,返回指针
    Stack S;
    S = (Stack)malloc(sizeof(struct SNode));
    S->Next = NULL;
    return S;
}

bool IsEmpty(Stack S)
{   // 判断堆栈s是否为空,若为空函数返回true,否则返回false
    return ( S->Next == NULL );
}

bool Push(ElementType item, Stack S)
{   // 将元素X压入堆栈S
    struct SNode *TmpCell;
    TmpCell = (struct SNode *)malloc(sizeof(struct SNode));
    TmpCell->Element = item;
    TmpCell->Next = S->Next;
    S->Next = TmpCell;
    return true;
}

ElementType Pop(Stack S)
{
    struct SNode *FirstCell;
    ElementType TopElem;
    if ( IsEmpty( S ) ) {
        printf("堆栈空"); return NULL;
    }
    else {
        FirstCell = S->Next;
        S->Next = FirstCell->Next;
        TopElem = FirstCell->Data;
        free(FirstCell);
        return TopElem;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值