数据结构(C语言版)第三章栈和队列 3.1

主要实现初始化、入栈、出栈、取栈顶值、输出栈内容等5个接口。

Stack.h

#ifndef _STACK_H
#define _STACK_H


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



#define STACK_INIT_SIZE    100
#define STACK_INCRE_SIZE    50

typedef int SElemType ;


typedef struct SqStack
{
    SElemType *base;
    SElemType *top;
    int stackSize;    
}Stack,*PStack;


int InitStack(PStack S);

int GetTop(PStack S,SElemType *e);

int Push(PStack S,SElemType e);

int Pop(PStack S,SElemType *e);

int ClearStack(PStack S);

int DestoryStack(PStack S);



#endif

Stack.c

#include "Stack.h"

/*3.1*/


int InitStack(PStack S)
{
    S->base = (SElemType *)malloc(sizeof(SElemType) * STACK_INIT_SIZE);

    if(!S->base)
    {
        exit(0);
    }

    S->top = S->base;
    S->stackSize = STACK_INIT_SIZE;

    return 1;
}


int GetTop(PStack S,SElemType *e)
{
    if(S->base == S->top)
    {
        return -1;
    }

    *e = *(S->top -1);

    return 1;
}

int Push(PStack S,SElemType e)
{
    if(S->top - S->base >= S->stackSize)
    {
        S->base = (SElemType *)realloc(S->base,(S->stackSize + STACK_INCRE_SIZE) * sizeof(SElemType));

        if(!S->base)
        {
            return -1;
        }

        S->top = S->base + S->stackSize;
        S->stackSize += STACK_INCRE_SIZE;
    }

    *S->top++ = e;

    return 1;
}

int Pop(PStack S,SElemType *e)
{
    if(S->base == S->top)
    {
        return -1;
    }
    *e = * -- S->top;
}


int ClearStack(PStack S)
{
    S->top = S->base;

    return 1;
}

int DestoryStack(PStack S)
{
    free(S->base);
}


void PrintStack(PStack S)
{
    PStack p;
    p = S;

    int i = 0;
    while(p->top != p->base)
    {
        i++;
        printf("%d\t",* -- p->top);
    }
    p->top += i;
    printf("\n");
}

Main_3_1.c

#include "Stack.h"


int main(int argc , char** argv)
{
    PStack p;

    p = (PStack)malloc(sizeof(Stack));

    if(!p)
    {
        return -1;
    }

    printf("Init Stack\n");
    InitStack(p);

    printf("Push \n");
    int i = 0;
    for(i = 0 ; i < 7; i++)
    {
        Push(p,i*7 - 1);
        printf("%d\t",i*7-1);
    }
    printf("\n");
    PrintStack(p);

    
    GetTop(p,&i);
    printf("the top of the stack is %d\n",i);

    printf("Pop\n");
    Pop(p,&i);
    PrintStack(p);

    printf("Clear\n");
    ClearStack(p);
    
    DestoryStack(p);

    return 1;
}

编译方法与前类似:

1. gcc Stack.c -fPIC -shared -o libStack.so

2.  gcc -o main_3_1 main_3_1.c ./libStack.so

运行结果(gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3):

root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3# ./main_3_1
Init Stack
Push
-1 6 13 20 27 34 41
41 34 27 20 13 6 -1
the top of the stack is 41
Pop
34 27 20 13 6 -1
Clear
root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3# gcc --version

原文地址:https://www.cnblogs.com/xiaowenhu/p/xiaotiger_4.html