堆栈和其代码的两种实现

/*************************************************************************
	> 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; 
}


版权声明:本文为u014270687原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。