栈的基本实现(C)

栈的基本实现

#include<iostream>
#include<stdio.h>
#include<malloc.h> 


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

typedef struct Stack {
    
    
	PNODE pTop;			//栈顶
	PNODE pBottom;		//栈底
}STACK,*PSTACK;

void initStack(PSTACK );
void pushStack(PSTACK, int);
bool popStack(PSTACK, int *);
void traverse(PSTACK);
bool empyt(PSTACK);
void clear(PSTACK pS);
void main() {
    
    
	
	STACK S;  //等价于struct Stack s;

	int val;
	initStack(&S); //目的创建一个空栈

	pushStack(&S, 1);
	pushStack(&S, 2);
	pushStack(&S, 5);
	pushStack(&S, 7);
	pushStack(&S, 9);

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

	if (popStack(&S,&val))
	{
    
    
		printf("出栈成功,出栈的元素是%d\n", val);
	}
	else {
    
    
	
		printf("出栈失败\n");
	}
	traverse(&S);
	clear(&S);
	traverse(&S);
	system("pause");
}

void initStack(PSTACK pS) {
    
    
	pS->pTop = (PNODE)malloc(sizeof(NODE));

	if (NULL == pS->pTop) {
    
    
		printf("动态内存分配失败!\n");
		exit(-1);
	}
	else {
    
    
		pS->pBottom = pS->pTop;

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


}

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

//把pS所指向的栈 出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败,返回false否则true
bool popStack(PSTACK pS, int* pVal) {
    
    

	if (empyt(pS))
	{
    
    
		return false;
	}
	else {
    
    
		PNODE r = pS->pTop;
		*pVal = r->data;
		pS->pTop = r->pNext;
		free(r);
		r = NULL;

		return true;
	}

}
//判断是否为空
bool empyt(PSTACK pS) {
    
    
	if (pS->pTop == pS->pBottom)
		return true;

	else
		return false;

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

	printf("\n");
	return;

}


//清空
void clear(PSTACK pS) {
    
    
	if (empyt(pS))
	{
    
    
		return;
	}
	else  {
    
    
		PNODE p = pS->pTop;

		PNODE q = NULL;
		while (p != pS->pBottom) {
    
    
			q = p->pNext;
			free(p);
			p = q;
			
		}
		pS->pTop = pS->pBottom;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42481940/article/details/106954366