栈-基本操作(C版)

栈(Stack) 是限制插入和删除只能在一个位置上进行的表,该位置是表额末端,叫栈的顶部(top)。

一般常有的操作有

/**判断堆栈是否为空栈**/
int isEmpty(Stack s)
/**判断堆栈是否已满**/
int isFull(Stack s)
/**入栈**/
void push(Stack s,int item)
/**出栈**/
int pop(Stack s)
/**取栈顶元素**/
int top(Stack s)

Stack.c

#include <stdio.h>
#include <stdlib.h>
#define EMPTYTOP -1;

/**定义一个堆栈**/
typedef struct StackRec{
	int size;//栈大小
	int top;//栈指针
	int *Array;
}LStack,*Stack;

/**栈指针指向栈底**/
void makeEmpty(Stack s){
	s->top = EMPTYTOP;
}

/**创建一个大小为size 的空栈**/
Stack createStack(int size){
	Stack stack;
	stack = (Stack)malloc(sizeof(LStack));
	if(stack==NULL){
		printf("error!");
		return NULL;	
	}
	stack->Array = malloc(sizeof(int)*size);
	if(stack->Array==NULL){
		printf("error!");
		return NULL;
	}
	stack->size = size;
	makeEmpty(stack);
	return stack;
}

/**判断堆栈是否为空栈**/
int isEmpty(Stack s){
	return s->top == EMPTYTOP;
}

/**判断堆栈是否已满**/
int isFull(Stack s){
	return s->top == s->size;
}

/**入栈**/
void push(Stack s,int item){
	if(isFull(s)){
		printf("the full Stack");
	} else {
		s->Array[++s->top] = item;
	}
}

/**出栈**/
int pop(Stack s){
	if(isEmpty(s)){
		printf("the Empty Stack");
	} else {
		return s->Array[s->top--];
	}
	return -1;
}

/**取栈顶元素**/
int top(Stack s){
	if(!isEmpty(s)){
		return s->Array[s->top];	
	}
	return -1;
}

/**释放空间**/
void disPoseStack(Stack s){
	if(s!=NULL){
		free(s->Array);
		free(s);	
	}
}

int main(void){
	int capacity = 10;
	Stack s = createStack(capacity);
	push(s,1);
	push(s,2);
	push(s,3);
	printf("%d\n",top(s));
	int x = pop(s);
	printf("%d\n",x);
	printf("%d\n",top(s));
	disPoseStack(s);
	return -1;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值