堆棧創建的兩種實例

順序存儲實現堆棧操作:

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章