C链栈基础

/*************************************************************************
	> File Name: stack.c
	> Author: XXDK
	> Email: v.manstein@qq.com 
	> Created Time: Tue 07 Mar 2017 04:22:40 AM PST
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
// 栈节点类型
struct stack_node {
	int data;
	struct stack_node* next;
};
// 栈头节点类型
struct stack_head {
	struct stack_node* top; // 栈顶指针top
	int n; // 栈深度
};

struct stack_head* create_empty_stack(void)
{
	struct stack_head* head = (struct stack_head*)malloc(sizeof(struct stack_head));
	
	printf("create ok.\n");
	if(head == NULL) {
		printf("allocate memory failed.");
	}
	head -> n = 0;
	head -> top = NULL;
	printf("create ok.\n");

	return head;
}

int push_stack(struct stack_head * head, int data)
{
	struct stack_node* node = (struct stack_node*)malloc(sizeof(struct stack_node));

	if(node == NULL) {
		printf("node allocate memory failed\n");
		return -1;
	}
	printf("push ok\n");
	node->data = data;
	node->next = head->top;
	head->top = node;
	head->n++;
	

	return 0;
}

int pop_stack(struct stack_head* head)
{
	struct stack_node* temp;

	if(head == NULL){
		printf("stack invalid");
	}
	while(head->top != NULL) {
		printf("[%d] ", head->top->data);
		temp = head->top;
		head->top = head->top->next;
		free(temp);
	}

	return 0;
}

int get_stack_top(struct stack_head* head)
{
	if(head == NULL) {
		printf("stack invalid");
	}
	if(head->top == NULL) {
		printf("stack empty.\n");
	}else 
		return head->top->data;
}

int stack_empty(struct stack_head* head)
{
	if(head == NULL) {
		printf("stack invalid\n");
	}
	return (head->top == NULL) ? 0 : 1;

}


int main()
{
	struct stack_head* head = create_empty_stack();
	int a[] = {1,2,3,4,5,6};

	for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
		push_stack(head, a[i]);
	}
	pop_stack(head);

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值