栈-顺序栈

定义:栈是限定仅在表尾进行删除插入和删除操作的线性表。
把允许插入和删除的一端叫做栈顶top,另一端成为栈低bottom,,不含任何数据元素的栈称为空栈。(Last In First Out)的线性表。
栈是线性表的特例
1.对于线性表来说,用数组下标为0的一端作为栈底比较好,因为首元素都在栈底,变化最小,所以让它做栈底。
明确:
1.top指示栈顶元素在数组的位置
2.top=0表示存在一个元素(与数组下标一致)
3.top=-1表示栈为空

顺序栈的长度为O(1);

#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */

typedef int Status;
typedef int SElemType;
//顺序栈结构
typedef struct {
    SElemType data[MAXSIZE];
    int top;                //栈顶指针
}SqStack;

//进栈push 时间复杂度O(1)
Status Push(SqStack *S,SElemType e){
    if(S->top == MAXSIZE-1){//栈满
        return ERROR;
    }
    S->top++;              //栈顶指针加1
    S->data[S->top]=e;      //移动后的栈顶指针赋值
    return OK;
}

//出栈pop
Status Pop(SqStack *S,SElemType *e){
    if(S->top == -1){       //栈中没有元素
        return ERROR;
    }
    *e=S->data[S->top];
    S->top--;
    return OK;
}

Status InitStack(SqStack *S){ //初始化栈
    S->top=-1;
    return OK;
}

Status DestoryStack(SqStack *S){    //若栈存在销毁
    ;
}

Status ClearStack(SqStack*S){
    S->top=-1;
    return OK;
}

Status EmptyStack(SqStack S){
    if(S.top == -1){
        return TRUE;
    }else{
        return FALSE;
    }
}

Status GetTop(SqStack S , SElemType *e){
    if(EmptyStack(S))
        return ERROR;
    *e = S.data[S.top];
        return OK;
}

int StackLength(SqStack S){
   return S.top+1;
}
int main()
{
            SqStack s;
            InitStack(&s);          //不要忘记初始化栈
            int i=0;
            for(;i<10;i++){
                Push(&s,i);
            }
            i=0;
            printf("栈的top指针为%d\n",s.top);
            while(i<=s.top){
                printf("%d\n",s.data[i]);
                i++;
            }



            printf("测试出栈\n");
            int value;
            while(s.top!=-1){
                Pop(&s,&value);
                printf("%d\n",value);
            }
            printf("栈的top指针为%d\n",s.top);


            printf("测试栈为空\n");
            printf("%d\n",EmptyStack(s));


            printf("测试返回栈内的栈顶元素\n");
            i=0;
            printf("向栈中插入10个元素\n");
            for(;i<10;i++){
                Push(&s,i+1);
            }
            printf("栈的top指针为%d\n",s.top);
            int result;
            GetTop(s,&result);
            printf("栈顶的数据为%d\n",result);
            printf("栈的长度为%d\n",StackLength(s));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值