数据结构学习之路(三)栈的简单实现

简单实现了栈的基本功能,如果有写的不妥的地方烦请联系我。留言,或者文章下方的邮箱都可以。

我是在mac系统下写的,所以需要include的包可能和其他系统略有不同。

# include 
# include 

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

typedef struct Stack{
	struct Node * pButtom;
	struct Node * pTop;
}*PSTACK, STACK;

void init(PSTACK);

void showStack(PSTACK);

bool isEmpty(PSTACK);

bool push(PSTACK, int);

bool pop(PSTACK, int *);

bool clear(PSTACK);


int main(void){
	PSTACK pStack;
	init(pStack);
	showStack(pStack);
	push(pStack, 5);
	push(pStack, 1);
	push(pStack, 4);
	push(pStack, 9);
	showStack(pStack);
	int val;
	pop(pStack, &val);
	printf("%d\n", val);
	showStack(pStack);
	clear(pStack);
	showStack(pStack);
	return 0;
}

void init(PSTACK pStack){
	pStack->pButtom = (PNODE)malloc(sizeof(NODE));
	if (pStack->pButtom==NULL){
		printf("%s\n", "内存分配失败!");
		exit(-1);
	}
	pStack->pTop = pStack->pButtom;
	pStack->pTop->pNext=NULL;
	printf("%s\n", "栈初始化成功!");
	return;
}

void showStack(PSTACK pStack){
	if (isEmpty(pStack)){
		printf("%s\n", "栈为空!");
		return;
	}
	PNODE p = pStack->pTop;

	while(p!=pStack->pButtom){
		printf("%d  ", p->data);
		p = p->pNext;
	}
	printf("\n");
	return;
}

bool push(PSTACK pStack, int val){
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if (pNew==NULL){
		printf("%s\n", "内存分配失败!");
		return false;
	}

	pNew->data = val;
	pNew->pNext = pStack->pTop;
	pStack->pTop = pNew;
	return true;
}

bool pop(PSTACK pStack, int * val){
	if (isEmpty(pStack)){
		printf("%s\n", "栈为空,出栈失败!");
		return false;
	}

	PNODE p = pStack->pTop;
	pStack->pTop = p->pNext;
	* val = p->data;
	free(p);
	return true;
}

bool clear(PSTACK pStack){
	if (isEmpty(pStack)){
		printf("%s\n", "栈为空,清空失败!");
		return false;
	}
	
	PNODE p = pStack->pTop;
	PNODE q = NULL;
	while(p != pStack->pButtom){
		q = p->pNext;
		free(p);
		p = q;
	}

	pStack->pTop = pStack->pButtom;
	return true;
}


bool isEmpty(PSTACK pStack){
	if (pStack->pTop == pStack->pButtom)
		return true;
	return false;
}

email: [email protected]


版权声明:博客编写不易,转载时请注明出处,万分感谢 !

https://blog.csdn.net/zyy_2018/article/details/79765642



你可能感兴趣的:(数据结构学习)