数据结构之链栈的基本操作(C语言实现)

链栈的基本操作:初始化,出栈,入栈,判空,遍历,清空

#include
#include
#include
#include

typedef struct Node
{
	int data;
	struct Node* pNext;
}NODE,*PNODE;

typedef struct Stack
{
	PNODE pTop;
	PNODE pBottom;

}STACK,*PSTACK;

void init(PSTACK); //PSTACK 等价于struct STACK *
void push(PSTACK ,int );
void traverse(PSTACK);
bool pop(PSTACK, int*);
bool empty(PSTACK pS);
void clear(PSTACK pS);

int main(void)
{
	STACK S;
	int val;
	init(&S);
	push(&S,1);
	push(&S, 2);
	push(&S, 3);
	push(&S, 4);
	push(&S, 5);
	traverse(&S);//遍历输出
	if (pop(&S, &val))
	{
		printf("出栈成功,出栈的元素是%d\n", val);

	}
	else
	{
		printf("出栈失败");
	}
	traverse(&S);
	clear(&S);
	
	return 0;
}
//初始化
void init(PSTACK pS)
{

	pS->pTop = (PNODE)malloc(sizeof(NODE));
	if (NULL == pS->pTop)
	{
		printf("分配失败");
		exit(-1);
	}
	else
	{
		pS->pBottom = pS->pTop;
		pS->pTop->pNext = NULL;
	}
}
//压栈(入栈)
void push(PSTACK pS, int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if(pNew){

		pNew->data = val;
		pNew->pNext = pS->pTop;
		pS->pTop = pNew;
		
	}
}
//遍历
void traverse(PSTACK pS)
{
	PNODE p;
	p = pS->pTop;
	while (p != pS->pBottom)
	{
		printf("%d ", p->data);
		p = p->pNext;
	}
	printf("\n");

}
//判空
bool empty(PSTACK pS)
{
	if (pS->pBottom == pS->pTop)
		return true;
	else
		return false;
	
}
//出栈
bool pop(PSTACK pS, int* pVal)
{
	if (empty(pS))
	{
		return false;
	}
	else
	{
		PNODE r = pS->pTop;
		*pVal = r->data;
		pS->pTop = r->pNext;
		free(r);
		r = NULL;

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

	}

}

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