堆栈创建的两种实例

顺序存储实现堆栈操作:

#include <stdio.h>
#include <stdlib.h>
typedef int ElementType,Position;
struct SNode{
    ElementType *Data;/*存储元素的数组*/
    Position Top;/*栈顶指针*/
    int MaxSize;/*堆栈最大容量*/
};
typedef struct SNode *Stack;


Stack CreateStack(int MaxSize)
{
    Stack S=(Stack)malloc(sizeof(struct SNode));//申请空间
    S->Data=(ElementType*)malloc(MaxSize * sizeof(ElementType));
    S->Top=-1;//栈顶初始化为-1
    S->MaxSize=MaxSize;
    return S;
}
bool IsFull(Stack S)//判断堆栈S是不是满
{
    return(S->Top==S->MaxSize-1); //栈顶指针指向的值是否等于最大容量的值
}
bool Push(Stack S,ElementType X)//将X压入栈S顶
{
    if(IsFull(S)){
        printf("堆栈满");
        return false;
    }
    else{
        S->Data[++(S->Top)]=X;//栈顶s+1,将其data赋值为X
        return true;
    }
}
bool IsEmpty(Stack S)
{
    return(S->Top==-1);//栈顶指向-1即为空
}
ElementType Pop(Stack S)
{
    while(!IsEmpty(S)){
        return (S->Data[(S->Top)--]);//返回栈顶s->data[s->top],栈顶下降s->top--
    }
}
int main()
{
    Stack m;
    m=CreateStack(4);
    int i=0;
    while(!IsFull(m)){
        Push(m,i++);
    }
    while(!IsEmpty(m)){
        printf("%d",Pop(m));
    }
    return 0;

}

**

链式存储实现堆栈操作

**

#include <stdlib.h>
#include <stdio.h>

typedef int ElementType;
typedef struct SNode *PtrToSNode;
struct SNode{
    ElementType Data;
    PtrToSNode Next;
};
typedef PtrToSNode Stack;
Stack CreateStack()
{//创建堆栈
    Stack S;
    S=(Stack)malloc(sizeof(struct SNode));
    S->Next=NULL;
    return S;
}
bool IsEmpty(Stack S)
{//判断堆栈是否为空
    return (S->Next==NULL);
}
bool Push(Stack S,ElementType X)
{//将X压入栈顶S
    PtrToSNode TmpCell;
    TmpCell=(PtrToSNode)malloc(sizeof(struct SNode));
    TmpCell->Data=X;
    TmpCell->Next=S->Next;
    S->Next=TmpCell;
    return true;
}
ElementType Pop(Stack S)
{//将栈顶元素弹出
    PtrToSNode FirstCell;
    ElementType TopElem;
    while(!IsEmpty(S)){
        FirstCell=S->Next;
        TopElem=FirstCell->Data;
        S->Next=FirstCell->Next;
        free(FirstCell);
        return TopElem;
    }
}
int main()
{
    Stack S;
    int n,i;
    S=CreateStack();
    printf("请输入需要创建的堆栈大小:");
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        Push(S,i);
    }
    while(!IsEmpty(S)){
        printf("%d ",Pop(S));
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章