栈的基本操作

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

#define MAXSIZE 5
#define LEN sizeof(SqStack)

typedef struct 
{
    int data[MAXSIZE];
    int top;
}SqStack;

SqStack *S;

void InitStack()
{
    S = (SqStack*)malloc(LEN);
    if(!S)
    {
        perror("malloc");
        exit(1);
    }
    S -> top = -1;
}

void Push()
{
    int e;
    printf("Please input value:");
    scanf("%d",&e);
    if(S -> top == MAXSIZE - 1)
    {
        printf("Stack Full!\n");
    }
    (S -> top)++;
    printf("S -> top = %d\n",S -> top);
    S -> data[S -> top] = e;
}

void Pop()
{
    if(S -> top == -1)
        printf("Stack NULL!\n");
    S -> top--;
}

int ClearStack()
{
    S -> top = -1;
    return 1;
}

void StackEmpty()
{
    if(S -> top == -1)
        printf("StackEmpty!\n");
    else
        printf("Stack Not Empty!\n");
}

void StackLength()
{
    printf("length = %d\n",S -> top + 1);
}

void DestroyStack()
{
    S -> top = -1;
    free(S);
    S = NULL;
}

void GetTop()
{
    if(S -> top == -1)
    {
        printf("Top NULL!\n");
    }
    else
    {
        printf("topdata = %d\n",S -> data[S -> top]);
    }
}

void StackTraverse()
{
    int i = S -> top;
    printf("S -> top = %d\n",S -> top);
    while(i != -1)
    {
        printf("stackdata = %d\n",S -> data[i]);
        i--;  
    }

}

int main()
{
    int n;
    while(1)
    {
        printf("1.Init 2.Push 3.Pop 4.Clear 5.Empty 6.Length\n 7.Destroy 8.GetTop 9.Print 10.Exit\n");
        printf("Please input num:");
        scanf("%d",&n);
        switch(n)
        {
            case 1:InitStack();break;
            case 2:Push();break;
            case 3:Pop();break;
            case 4:ClearStack();break;
            case 5:StackEmpty();break;
            case 6:StackLength();break;
            case 7:DestroyStack();break;
            case 8:GetTop();break;
            case 9:StackTraverse();break;
        }
        if(n == 10)
            break;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值