堆栈和其代码的两种实现

/*************************************************************************
	> File Name: stack1.c
	> Author: RoseSec
	> Mail: rosesecno1@hotmail.com 
	> Created Time: Tue 31 May 2016 12:05:08 PM EDT
 ************************************************************************/

#include<stdio.h>
#include <stdbool.h>

#define LISTSIZE 10
typedef int DataType;

typedef struct
{
	DataType data[LISTSIZE];
	int top;
} Stack;

void init(Stack *stack)
{
	stack->top = 0;
}

bool empty(Stack *stack)
{
	return stack->top == 0;
}

void push(Stack *stack, DataType d)
{
	if(stack->top == LISTSIZE)
		return;
	stack->data[stack->top++] = d;
}

void pop(Stack *stack)
{
	if(empty(stack))
		return;
	stack->top--;
}

DataType topData(Stack *stack)
{
	return stack->data[stack->top - 1];
}

int main()
{
	Stack stack;
	init(&stack);
	push(&stack, 30);
	push(&stack, 60);
	push(&stack, 80);

	while(!empty(&stack))
	{
		printf("%d ", topData(&stack));
		pop(&stack);
	}

	printf("\n");
	return 0;
}
===========================================================================
/*************************************************************************
	> File Name: stack2.c
	> Author: RoseSec
	> Mail: rosesecno1@hotmail.com 
	> Created Time: Tue 31 May 2016 12:19:08 PM EDT
 ************************************************************************/

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

typedef int DataType;

typedef struct node
{
	DataType data;
	struct node *next;
} Stack;

void init(Stack **top)
{
	*top = NULL;
}

bool empty(Stack *top)
{
	return top == NULL;
}

void push(Stack **top, DataType d)
{
	Stack *newNode = (Stack *)malloc(sizeof(Stack));
	newNode->data = d;
	newNode->next = *top;
	*top = newNode;
}

void pop(Stack **top)
{
	if(empty(*top))
		return;
	Stack *tempNode = *top;
	*top = (*top)->next;
	free(tempNode);
}

int topData(Stack *top)
{
	if(empty(top))
		return -1;
	return top->data;
}

int main()
{
	Stack *head;
	
	init(&head);
	push(&head, 10);
	push(&head, 20);
	push(&head, 11);
	push(&head, 12);
	push(&head, 91);
	push(&head, 93);

	while(!empty(head))
	{
		printf("%d, ", topData(head));
		pop(&head);
	}
	






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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值