1. 程式人生 > 其它 >棧、佇列、陣列

棧、佇列、陣列

定義

#include <stdio.h>

/*
棧
    只允許在棧頂插入刪除操作的線性表
    Last Insert First Out.
*/

// 順序棧

#define MaxSize 10

typedef struct 
{
    int data[MaxSize];  // 靜態陣列存放棧元素
    int top;  // 棧頂指標
} SqStack;

棧頂指標指向棧頂元素的棧 空為-1

// 棧頂指標指向棧頂元素 空為-1

void InitStack1(SqStack &S)
{
    S.top = -1;  // 棧空
}

void Push1(SqStack &S, int x)
{
    S.data[++S.top] = x;
}

int  Pop1(SqStack &S)
{   
    int x;
    x = S.data[S.top--];
    return x;
}

int GetTop1(SqStack S)
{
    return S.data[S.top];
}

測試

int main()
{
    SqStack S;
    InitStack1(S);

    for(int i=1; i<=5; i++)
    {
        Push1(S, i);
    }
    

    puts("after push...");
    show1(S);
    puts("pop....");
    while( S.top != -1)
    {
        int x = Pop1(S);
        printf("%i\n", x);
    }
    

    return 0;
}

void show1(SqStack S)
{
    for(int i=S.top; i!=-1; i--)
    {
        printf("| %i |\n", S.data[i]);
        puts("-----\n");
    }
         
}

棧頂指標指向下一個元素存放位置的棧 空為 0

// 棧頂指標指向下一個元素存放位置 空為 0

void InitStack0(SqStack &S)
{
    S.top = 0;  // 棧空
}

void Push0(SqStack &S, int x)
{
    S.data[S.top++] = x;
}

void Pop0(SqStack &S)
{
    int x;
    x = S.data[--S.top];
}

int GetTop0(SqStack S)
{
    int x;
    x = S.data[S.top - 1];
    return x;
}

共享棧

// 共享棧
typedef struct
{
    int data[MaxSize];
    int topa;  // 棧a 以下方為棧底 的棧頂指標
    int topb;  // 棧b 以上方位棧底 的棧頂指標
}ShStack;

void InitShStack(ShStack &S)
{
    S.topa = -1;
    S.topb = MaxSize;
}

bool isFull(ShStack S)  // 棧是否已滿
{
    return S.topa + 1 == S.topb;
}

bool Pusha(ShStack &S, int x)
{
    if(isFull(S) == true)
    {
        return false;
    }
    S.data[++S.topa] = x;

    return true;
}

bool Pushb(ShStack &S, int x)
{
    if(isFull(S) == true)
    {
        return false;
    }
    S.data[++S.topb] = x;

    return true;
}

int Popa(ShStack &S)
{
    return S.data[S.topa--];
}

int Popb(ShStack &S)
{
    return S.data[S.topb--];
}

佇列

陣列