数据结构 - C语言版 - 顺序栈 所有基本操作

C语言 - 顺序栈 所有基本操作

//结构体 定义为 数组 的方式
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 5

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


Stack *Init_SeqStack()
{
    Stack *s;
    s=malloc(sizeof(Stack));
    s->top = -1;
    return s;
}

void Push_Stack(Stack * S)
{
	int i;

	for(i=0; i<MAXSIZE; i++)
	{
		if(S->top== (MAXSIZE-1) )
		{
			printf("栈满,无法继续输入!\n");
			break;
		}
		
		S->top++;       

		scanf("%d", &S->data[S->top] );
	}
}


void Pop_Stack(Stack * S)
{
	
	while(S->top != -1)
	{
		printf("%d ",S->data[S->top]);

        S->top--;
	}
}

int main(void)
{
	Stack *S;
      
    S = Init_SeqStack();

	Push_Stack(S);
	Pop_Stack(S);

	printf("\n");
	system("pause");
	return 0;
}

//结构体 定义为 数组基地址 的方式
#include <stdio.h>
#define MAXSIZE 100
typedef int SElemType;
typedef struct
{
    SElemType *base;
	SElemType *top;
    int stacksize;
}SqStack;
SqStack S;
int  InitStack(SqStack *S)
{
    S->base= malloc(sizeof(SElemType[MAXSIZE]));
    if(!S->base) return 0;
    S->top = S->base;
    S->stacksize=MAXSIZE;
	return 1;
}

int Push(SqStack *S,SElemType e)
{
    if((S->top)-(S->base) == S->stacksize) 
		return 0;
    else
    {
        *S->top++=e;
       
        return 1;
    }
}
int Pop(SqStack *S,SElemType *e)
{
    if(S->top==S->base) return 0;
    else
    {
        *e = *--S->top;
       
        return 1;
    }
}

main()
{
    int a;
	InitStack(&S);
    Push(&S,1);
	Push(&S,2);
	Push(&S,3);
	Push(&S,4);
	Push(&S,5);
	Pop(&S,&a);
	printf("%d\n",a);
	Pop(&S,&a);
	printf("%d\n",a);
	Pop(&S,&a);
	printf("%d\n",a);
	Pop(&S,&a);
	printf("%d\n",a);
	Pop(&S,&a);
	printf("%d\n",a);

}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值