(程序员面试题)链栈的基本操作

链栈的基本操作有如下几种:入栈,出栈,判断栈满,判断栈空,遍历栈


详情请见testcase:

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

#define STACK_MAX 3

typedef struct stack {
	char data[10];
	struct stack *next;
} *st_ptr;

int is_stack_empty(st_ptr top) {
	if (top->next) {
		return -1;
	}
	return 0;
}

int is_stack_full(st_ptr top) {
	st_ptr tmp = top;
	int cur = 0;
	while (tmp->next) {
		cur++;
		tmp = tmp->next;
	}
	if (cur == STACK_MAX) {
		return 0;
	}
	return -1;
}

void print_stack(st_ptr top) {
	st_ptr tmp = top;
	while (tmp->next) {
		printf("%s\n", tmp->next->data);
		tmp = tmp->next;
	}
	printf("\n");
}

int push_stack(st_ptr top, st_ptr pop) {
	if (is_stack_full(top) == 0) {
		printf("stack full, can not push\n");
		return -1;
	}

	pop->next = top->next;
	top->next = pop;
	return 0;
}

int pop_stack(st_ptr top) {
	if (is_stack_empty(top) == 0) {
		printf("stack empty, can not pop\n");
		return -1;
	}
	
	top->next = top->next->next;
	return 0;
}

int main() {
	st_ptr top, cheny, cherry, new, test;
	top = (st_ptr)malloc(sizeof(struct stack));
	cheny = (st_ptr)malloc(sizeof(struct stack));
	cherry = (st_ptr)malloc(sizeof(struct stack));
	new = (st_ptr)malloc(sizeof(struct stack));
	test = (st_ptr)malloc(sizeof(struct stack));

	// this is an empty stack
	top->next = NULL;
	if (is_stack_empty(top) == 0) {
		printf("stack empty\n\n");
	}
	
	strcpy(cheny->data, "cheny");
	push_stack(top, cheny);
	print_stack(top);

	strcpy(cherry->data, "cherry");
	push_stack(top, cherry);
	print_stack(top);

	strcpy(new->data, "new");
	push_stack(top, new);
	print_stack(top);

	if (is_stack_full(top) == 0) {
		printf("stack full\n\n");
	}
	push_stack(top, test);

	pop_stack(top);
	pop_stack(top);
	print_stack(top);

	pop_stack(top);
	if (is_stack_empty(top) == 0) {
		printf("stack empty\n\n");
	}
	pop_stack(top);

	return 0;
}

运行结果如下:

stack empty

cheny

cherry
cheny

new
cherry
cheny

stack full

stack full, can not push
cheny

stack empty

stack empty, can not pop



程序的大致意思是:建立一个空栈,然后入栈3个元素(栈的空间是3),所以此时栈满,不能再入栈了(结果有打印哦),然后出栈2个,此时遍历栈(栈中只有1个了),然后再出栈1个,所以此时栈空,不能再出栈了(结果也有打印哦)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值