栈程序的演示

栈程序的演示,第1张

栈程序的演示
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
# include 

typedef struct Node
{
	int data;//数据
	struct Node * pNext;//指针域
}NODE, * PNODE;
typedef struct Stack

{
	PNODE pTop;
	PNODE pBottom;
}STACK ,*PSTACK;
void init_Stack(PSTACK);//初始化
void Push(PSTACK, int);//压栈
void traverse(PSTACK);//遍历栈
bool pop(PSTACK,int *);//出栈
bool empty(PSTACK pS);//判断栈是否为空
void clear(PSTACK);//清除栈
int main()
{
	STACK S;
	int val;
	init_Stack(&S);//目的是造出一个空栈
	Push(&S, 3);
	Push(&S, 4);
	Push(&S, 5);
	Push(&S, 6);
	traverse(&S);
	if (pop(&S, &val))
	{
		printf("出栈成功,出栈的元素是%dn", val);
	}
	else
	{
		printf("出栈失败!n");
	}
	traverse(&S);
	clear(&S);
	traverse(&S);
	return 0;
}






void init_Stack(PSTACK pS)
{
	pS->pBottom = (PNODE)malloc(sizeof(NODE));
	if (NULL == pS->pBottom)
	{
		printf("动态内存分配失败!n");
		exit(-1);
	}
	else
	{
		pS->pTop = pS->pBottom;
		pS->pBottom->pNext = NULL;
	}
}

void Push(PSTACK pS, int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	pNew->data = val;
	pNew->pNext = pS->pTop;
	pS->pTop = pNew;
	return;
}

void traverse(PSTACK pS)
{
	PNODE p = pS->pTop;
	while (p->pNext!=NULL)
	{
		printf("%d ", p->data);
		p = p->pNext;
	}
	printf("n");
}

bool empty(PSTACK pS)
{
	if (pS->pTop == pS->pBottom)
		return true;
	else
		return false;
}
//把pS所指向的栈出栈一次,并把出栈的元素存入Val形参所指向的变量中,如果出栈失败,返回false,否则返回true
bool pop(PSTACK pS,int * val)
{
	if (empty(pS)) //pS本身存放的就是S的地址
	{
		return false;
	}
	else
	{
		PNODE p = pS->pTop;
		*val = p->data;
		pS->pTop = pS->pTop->pNext;
		free(p);
		p = NULL;
		return true;
	}
}

void clear(PSTACK pS)
{
	if (empty(pS))
	{
		return;
	}
	else
	{
		PNODE p = pS->pTop;
		while (p!=pS->pBottom)
		{
			PNODE q = p->pNext;
			free(p);
			p = q;
		}
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5657796.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存