关于c:C语言实现顺序栈的基本操作举例

45次阅读

共计 1884 个字符,预计需要花费 5 分钟才能阅读完成。

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define MaxSize 100
#define true 1
#define error 0
#define OK 1
#define OVERFLOW -2
typedef int ElemType;
typedef struct {    // 程序栈构造(动静)ElemType* top;
    ElemType* base;
    int stacksize;
}Sqstack;
int InitStack(Sqstack* s);   // 初始化 (在 C 语言中,形参和实参是单向传递,但可用指针(*) 传递地址,让形参影响实参,达到双向传递)
int EmptyStack(Sqstack* s);
int Push(Sqstack* s,ElemType e); // 插入元素 (在 c ++ 中,能够用(&) 援用型参数实现双向传递)
int StackLength(Sqstack* s);  // 元素长度
int StackPrint(Sqstack* s);  // 打印元素
int Pop(Sqstack* s); // 删除栈顶元素
int DestroyStack(Sqstack* s);  // 销毁栈
int main()
{
    int n;
    ElemType e, a;
    Sqstack *s;
    s = (Sqstack*)malloc(sizeof(Sqstack));  // 敲黑板重点!指针要有地址!记住调配地址!InitStack(s);
    printf("请输出插入元素个数:");
    scanf("%d", &n);
    printf("请输出插入元素:");
    for (int i = 0; i < n; i++) {scanf("%d", &e);
        Push(s, e);
    }
    if (EmptyStack(s) == 1)
        printf("** 啊!*** 空表 **\n");
    printf ("元素长度:%d\n",StackLength(s));
    printf("打印元素为:");
    StackPrint(s); 
    printf("\n");
    a = Pop(s);   // 我在这里翻了车,后面 Pop(s)没赋值 a,导致 Pop(s)援用两次,引发谬误。if (a == -2)
        printf("栈底溢出!\n");
    else
        printf("删除栈顶元素为:%d\n", a);
    printf("删除后:");
    StackPrint(s);
    printf("\n");
    system("pause");
    printf("销毁栈中.........\n");
    Sleep(3000);
    system("cls");
    if (DestroyStack(s) == 1)
        printf("销毁胜利!");
    else
        printf("销毁失败!");

    return 0;
}
int InitStack(Sqstack* s)
{s->base = (ElemType*)malloc(sizeof(ElemType) * MaxSize);
    if (!s->base)
        return error;
    s->top = s->base;
    s->stacksize = MaxSize;
    return OK;
}
int EmptyStack(Sqstack* s)
{if (s->base == s->top)
        return true;
    else
        return error;
}
int Push(Sqstack* s, ElemType e)
{if (s->top - s->base >= MaxSize)
        return OVERFLOW;
    if (!s->base)
        return error;
    *(s->top) = e;
    s->top++;
    return OK;
}

int StackLength(Sqstack* s)
{if (s->base == s->top)
        return error;
    else
        return ((s->top) - (s->base));
}
int StackPrint(Sqstack* s)
{if (s->base == NULL)
        return error;
    if (s->base == s->top)
        printf("没有元素!");
    ElemType* p;
    p = s->base;
    while (p <(s->top))
    {printf("%d", *p);
        p++;
    }
    return OK;
}
int Pop(Sqstack* s)
{
    ElemType a;
    if (s->base == s->top)
        return OVERFLOW;
    else {a = *(s->top-1);
        s->top--;
    }
    return a;
}
int DestroyStack(Sqstack* s)
{free(s);
    s->base = s->top = NULL;
    s->stacksize = 0;
    return OK;
}

正文完
 0