数据结构_P15

# include 
# include 
# include 
/*
*	动态栈(链表栈)的实现:初始化、入栈、出栈、遍历、判断为空、清空
*	栈底pBottom指向的不是最先进入的有效节点,而是一个空结点,入栈与出栈时操作pTop就可以了。
*	2016年6月14日15:12:50
*/

typedef struct Node		//链表节点数据类型的定义
{
	int data;
	struct Node* pNext;
}NODE, *PNODE;

typedef struct Stack	//栈数据类型的定义
{
	PNODE pTop;
	PNODE pBottom;		//注!:栈底是空节点!
}STACK, *PSTACK;

void init(PSTACK);
void push(PSTACK, int);		//push链表栈永远不会满,所以总是成功,不需要返回值
bool pop(PSTACK, int*);			//pop有可能失败,所以需要返回值bool输出成功与否
void traverse(PSTACK);
bool empty(PSTACK);
void clear(PSTACK);		//clear清空栈(pTop==pBottom),destroy销毁栈(栈没了)

int main(void)
{
	STACK S;	//创建栈(栈中两节点值垃圾值)
	int val;	//val存放每次pop弹出的值,并要将其输出

	init(&S);	//初始化栈,给pTop、pBottom赋值
	traverse(&S);
	push(&S, 1);		//新节点入栈(压栈)
	push(&S, 2);
	push(&S, 3);
	traverse(&S);
	if( pop(&S, &val) )		//出栈(删除节点),将弹出的x值存放到val中,注意这里判断的写法
		printf("pop出栈成功,值为%d\n", val);
	else
		printf("pop出栈失败!\n");

	traverse(&S);		//遍历输出
	clear(&S);
	traverse(&S);

	return 0;
}

void init(PSTACK pStack)
{
	pStack->pBottom = (PNODE)malloc(sizeof(NODE));
	if( pStack->pBottom == NULL )
	{
		printf("动态内存分配失败,程序终止!");
		exit(-1);
	}
	else
	{
		pStack->pBottom = NULL;			//pStack->pBottom->data、pStack->pBottom->pNext都为NULL,即为空结点
		pStack->pTop = pStack->pBottom;
	}
	return;
}

void push(PSTACK pStack, int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if( pNew == NULL )
	{
		printf("动态内存分配失败,程序终止!");
		exit(-1);
	}
	else
	{
		printf("push一个元素:%d\n", val);
		pNew->data = val;
		pNew->pNext = pStack->pTop;
		pStack->pTop = pNew;
	}
	return;
}

bool pop(PSTACK pStack, int* pVal)
{
	if( empty(pStack) )
	{
//		printf("当前栈为空,pop失败!");		//舍! 不写这些乱七八糟的没条理,总的都在main函数用if判断后再写就行
		return false;
	}
	else
	{
		PNODE p = pStack->pTop;
		*pVal = p->data;
		pStack->pTop = p->pNext;
		free(p);
		p = NULL;			//这个写不写不影响运行,郝斌写了!

		return true;
	}
}

void traverse(PSTACK pStack)
{
	printf("遍历栈所有元素: ");
	PNODE p = pStack->pTop;

	while( p != pStack->pBottom)	//pStack->pBottom换成NULL也可以
	{
		printf("%d ", p->data);
		p = p->pNext;
	}
	printf("\n");
	return;
}

bool empty(PSTACK pStack)
{
	if( pStack->pBottom == pStack->pTop )
		return true;
	else 
		return false;
}

void clear(PSTACK pStack)
{
	if( empty(pStack) )
		return;
	else
	{
		while(pStack->pTop != pStack->pBottom)	//pStack->pBottom换成NULL也可以
		{
			PNODE p = pStack->pTop;
			pStack->pTop = pStack->pTop->pNext;
			free(p);
			p = NULL;
		}
	}	
}

你可能感兴趣的:(数据结构(C语言))