基于 Linux 的链栈代码

/*************************************************************************
  > File Name: stacklist.c
  > Author: Wenfei6316
  > Mail: [email protected] 
  > Created Time: 2018年06月17日 星期日 12时36分38秒
 ************************************************************************/

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

typedef int data_t;
typedef struct StackNode
{
	data_t data;
	struct StackNode *next;
}StackNode, *StackLink;

StackLink CreateEmptyStack(void);
void PushStack(StackLink stack, data_t value);
void PopStack(StackLink stack, data_t *value);
void DestroyLinkStack(StackLink stack);

int main(int argc, const char *argv[])
{
	data_t data;
	StackLink stack;
	stack = CreateEmptyStack();
	PushStack(stack, 20);
	PushStack(stack, 30);

	PopStack(stack, &data);
	printf("Pop: %d\n", data);
	PopStack(stack, &data);
	printf("Pop: %d\n", data);
	PopStack(stack, &data);
	printf("Pop: %d\n", data);
	
	PushStack(stack, 20);
	PushStack(stack, 30);
	
	DestroyLinkStack(stack);

	return 0;
}

//创建栈
StackLink CreateEmptyStack(void)
{
	StackLink stack;
	stack = (StackLink)malloc(sizeof(StackNode));
	if (stack == NULL)
	{
		perror("Create stack failed!\n");
		exit(EXIT_FAILURE);
	}
	stack->data = -1;
	stack->next = NULL;

	return stack;
}

//压栈
void PushStack(StackLink stack, data_t value)
{
	StackLink p;
	if (stack == NULL)
	{
		printf("Stack is error!\n");
		exit(EXIT_FAILURE);
	}
	
	p = (StackLink)malloc(sizeof(StackNode));
	if (p == NULL)
	{
		perror("Push stack error!");
		return ;
	}

	p->data = value;
	p->next = stack->next;
	stack->next = p;

	return ;
}

//弹栈
void PopStack(StackLink stack, data_t *value)
{
	StackLink p;
	*value = 0;
	if (stack == NULL)
	{
		printf("Popstack error!\n");
		return ;
	}
	if (stack->next == NULL)
	{
		printf("Stack is empty!\n");
		return ;
	}

	p = stack->next;
	*value = p->data;
	stack->next = p->next;
	free(p);
	p = NULL;
}

//销毁栈
void DestroyLinkStack(StackLink stack)
{
	StackLink p;
	if (stack == NULL)
	{
		printf("Stack is NULL!\n");
		return ;
	}

	p = stack->next;
	while (p != NULL)
	{
		stack->next = p->next;
		free(p);
		p = stack->next;
	}
	free(stack);
	p = NULL;
	stack = NULL;

	printf("Destroy stack success!\n");

	return ;
}

猜你喜欢

转载自blog.csdn.net/wenfei11471/article/details/80719398