欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

堆栈

程序员文章站 2022-07-15 14:21:00
...

- 堆栈

堆栈
*

堆栈的数组存储

1.定义

#define MaxSize
typedef struct SNode *Stack;
struct SNode{
        ElementType Data[MaxSize];
        int top;         //top是记录栈顶元素下标
}; 

2.push

void Push(Stack PtrS,ElementType item)
{
    if(Ptrs->top+1==MaxSize){
        printf(“堆栈满”);return;
    }else {
        PtrS->Data[++(Ptrs->top)]=item;        //执行两步操作,Ptrs->top的++,和赋值
        return;
    }
}

3.pop

ElementType Pop(Stack PtrS)
{
    if(PtrS->top==-1){
        printf(“堆栈空”);return ERROR;
    }else {
        return (PtrS->Data[(PtrS->top)--]);/        /执行两步操作,赋值,和Ptrs->top的--
}

4.两个堆栈的操作

堆栈

数组的链式存储

  • 注意:堆栈的链式存储top在头结点!!

1.定义
堆栈
2.push

void Push(ElementType item,Stack S)
{
    struct SNode *TmpCell;
    TmpCell=(struct SNode*)malloc(sizeof(struct SNode));
    TmpCell->Data=item;
    Temp->Next=S->next;
    S->Next=TmpCell;        //S还是指向该链式栈头结点
}

3.pop

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;
}