栈的存储方式

栈的顺序存储结构


#define ElemType int
#define Stack_Init_Szie 10

#define OK 1;
#define ERROR 0; 

typedef struct Node{
	ElemType* base;
	ElemType* top;
	int stackSize;//栈的实际大小 
}SqStack;


int	Init(SqStack &sq){
	sq.base=(ElemType *)malloc(Stack_Init_Szie*sizeof(ElemType));
	if(!sq.base){
		return ERROR;	
	}
	 
	sq.top=sq.base;
	sq.stackSize=Stack_Init_Szie;
	return OK;
}

ElemType GetTop(SqStack sq){
	if(sq.top!=sq.base){
		return *(--sq.top);
	}
	
	return ERROR;
}

//进栈 
int Push(SqStack &sq,ElemType value){
	if(sq.top-sq.base==sq.stackSize){
		return ERROR;
	}

	*sq.top++ = value;
	return OK;
}

//出栈 
int Pop(SqStack &sq,ElemType &value){
	if(sq.base==sq.top){
		printf("This Stack is empty!!\n");
		return ERROR;
	}
	value=*(--sq.top);
	return OK;
}

int GetStackLength(SqStack sq){
	
	return sq.top-sq.base;
}

栈的链式存储结构

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

#define ElemType int

#define OK 1
#define ERROR 0
#define Status int

typedef struct Node{
	ElemType data;	
	struct Node *next;
}StackLink;

void Init(StackLink	*&s){
	s=(StackLink*)malloc(sizeof(StackLink));
	s->next=NULL;
}

Status Push(StackLink *&s,ElemType value){
	StackLink *p;
	p=(StackLink *)malloc(sizeof(StackLink));
	p->data=value;
	p->next=s->next;
	s->next=p;
	return OK;
}

Status Pop(StackLink *&s,ElemType &value){
	StackLink *p=s->next;
	if(!s->next) return ERROR;//栈空 
	value=p->data;
	s->next=p->next;
	free(p);
	return OK;
}

void Print(StackLink *s){
	StackLink *pre=s->next;
	while(pre!=NULL){
		printf("%d\n",pre->data);
		pre=pre->next;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值