数据结构(6):栈的链式存储结构及其基本运算的实现

#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct snode
{
	ElemType data;
	struct snode *next;
}LinkSTACK;

/*初始化*/
void StackInitiate(LinkSTACK *head)
{
	head->next = NULL;
}

/*判断栈是不是空栈*/
int StackNotEmpty(LinkSTACK *head)
{
	if (head->next == NULL) 
		return 0;
	else 
		return 1;
}
/*入栈*/
int StackPush(LinkSTACK *spu, ElemType x)
{
	LinkSTACK *p;
	if ((p = (LinkSTACK *)malloc(sizeof(LinkSTACK))) == NULL)
	{
		printf("内存空间不足无法插入!\n");
		return 0;
	}

	p->data = x;
	p->next = spu->next; /*新结点链入栈顶*/
	spu->next = p;
	return 1;
}

/*出栈*/
int StackPop(LinkSTACK *spo, ElemType *d)
{
	LinkSTACK *p;
	p = (LinkSTACK *)malloc(sizeof(LinkSTACK));
	p = spo->next;
	if (p == NULL)
	{
		printf("堆栈已空出错!");
	}
	*d = p->data;
	spo->next = p->next;
	free(p);
	return 1;
}

/*获取栈顶元素*/
int StackTop(LinkSTACK *head, ElemType *d)
{
	LinkSTACK *p = head->next;
	if (p == NULL)
	{
		printf("堆栈已空出错!\n");
	}
	*d = p->data;
	return 1;
}

int main()
{
	LinkSTACK *stack;
	stack = (LinkSTACK *)malloc(sizeof(LinkSTACK));
	StackInitiate(stack);
	ElemType d1 = 1;
	ElemType d2 = 2;
	ElemType d3 = 3;
	StackPush(stack, d1);
	printf("栈中压入:%d\n", d1);
	StackPush(stack, d2);
	printf("栈中压入:%d\n", d2);
	StackPush(stack, d3);
	printf("栈中压入:%d\n", d3);

	ElemType *d4, *d5, *d6;
	d4 = (ElemType *)(malloc(sizeof(ElemType)));
	d5 = (ElemType *)(malloc(sizeof(ElemType)));
	d6 = (ElemType *)(malloc(sizeof(ElemType)));

	StackPop(stack, d4);
	printf("栈中弹出:%d\n", *d4);
	StackPop(stack, d5);
	printf("栈中弹出:%d\n", *d5);
	StackPop(stack, d6);
	printf("栈中弹出:%d\n", *d6);
	getchar();
	return 0;
}

运行结果:

数据结构(6):栈的链式存储结构及其基本运算的实现
思路参照:
https://blog.csdn.net/Dean_Deng/article/details/44279097

上一篇:迷宫算法,求解所有路径(DFS),(bug找了好久 )


下一篇:链栈