C語言——棧的基本運算在順序棧上的實現


頭文件

Seqstack.h

#define maxsize 6
//const int maxsize = 6;

// 順序棧

typedef struct seqstack
{
    int data[maxsize];
    int top; // 標志棧頂位置的變量
}SeqStk;

 

main.c

#include <stdio.h>
#include "Seqstack.h"

// 棧的基本運算在順序棧上的實現
// 1. 初始化
int InitStack(SeqStk *stk)
{
    stk->top = 0;
    return 1;
}
// 2. 判斷棧空
int EmptyStack(SeqStk *stk)
{
    if(stk->top == 0) return 1;
    else return 0;
}
// 3.進棧
int Push(SeqStk *stk, int x)
{
    if(stk->top == maxsize - 1)
    {
        printf("棧已滿\n");
        return 0;
    }
    else
    {
        stk->data[stk->top] = x;
        stk->top++;
        return 1;
    }
}
// 4. 出棧
int Pop(SeqStk *stk)
{
    if(EmptyStack(stk))
    {
        printf("下溢");
        return 0;
    }
    else
    {
        stk->top--;
        return 1;
    }
}
// 5. 取棧頂元素
int GetTop(SeqStk *stk)
{
    if(EmptyStack(stk)) return 0;
    else return stk->data[stk->top];
}

main()
{
    SeqStk stk;
    int i;
    i = InitStack(&stk);
    if(i) printf("初始化成功\n");
    else printf("初始化失敗\n");

    Push(&stk, 1);
    Push(&stk, 2);
    Push(&stk, 3);

    for(i = 0;i < 3;i++)
        printf("%d\n", stk.data[i]);

    printf("\n");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM