链栈的实现(双指针 带头结点) C语言版

 
/*
	带头结点,双指针的链栈实现
	作者:S_hmily
	日期:2011年8月31日
	编译环境:VC++6.0
*/
/*************************************************************/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
/*************************************************************/
#define TRUE	1
#define	FALSE	0

typedef struct node {
	int		data;
	struct node *pNext;
}Node, *pNode;

typedef struct{
	pNode	pTop;
	pNode	pBottom;
}STACK, *pSTACK;


/*************************************************************/
void init_stack(pSTACK pS);
void push_stack(pSTACK pS, int val);
int  pop_stack(pSTACK pS, int *pVal);
void traverse(pSTACK pS);
int  empty(pSTACK pS);
/*************************************************************/
int main(void)
{
	STACK stack;
	int val;
	init_stack(&stack);
	push_stack(&stack, 1);
//	traverse(&stack);
	if (pop_stack(&stack, &val))
		printf("出栈的元素是%d\n", val);
	else
		printf("栈空\n");
//	traverse(&stack);
	return 0;
}


/*************************************************************/
void init_stack(pSTACK pS)
{
	pS->pTop  = (pNode)malloc(sizeof(Node));
	if (NULL == pS->pTop) {
		printf("动态内存分配失败");
		exit(-1);
	}

	pS->pBottom = pS->pTop;
	pS->pBottom->pNext = NULL;
}

/*************************************************************/
void push_stack(pSTACK pS, int val)
{
	pNode pNew = (pNode)malloc(sizeof(Node));
	if (NULL ==pNew) {
		printf("动态内存分配失败");
		exit(-1);
	}

	pNew->data = val;
	pNew->pNext = pS->pTop;
	pS->pTop = pNew;
}

/*************************************************************/
void traverse(pSTACK pS)
{
	pNode p = pS->pTop;

	while (p != pS->pBottom) {
		printf("%d ", p->data);
		p = p->pNext;
	}
}
/*************************************************************/
int  empty(pSTACK pS)
{
	if (pS->pTop == pS->pBottom)
		return TRUE;
	else
		return FALSE;
}

/*************************************************************/
int pop_stack(pSTACK pS, int *pVal)
{
	pNode p = pS->pTop;

	if ( empty(pS) )
		return FALSE;

	*pVal = p->data;
	pS->pTop = p->pNext;
	free(p);
	p = NULL;
	return TRUE;
}
/*************************************************************/

你可能感兴趣的:(c,struct,null,语言)