【菜鸟er】C语言数据结构_动态栈应用

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//#include <bits/stdc++.h>
//using namespace std;

//链表定义
typedef struct node{
    int data;
    struct node * pnext;
}NODE,*PNODE;

typedef struct stack{
	PNODE ptop;
	PNODE pbottom;
}STACK,* PSTACK;
//初始化栈
void init_stack(PSTACK ps);
//压栈
void push_stack(PSTACK ps,int val);
//遍历
void traverse_stack(PSTACK ps);
//出栈
bool pop_stack(PSTACK ps,int * pval);
//判断空
bool empty_stack(PSTACK ps);
//清空
void clear_stack(PSTACK ps);

int main()
{
	STACK s;
	init_stack(&s);

	push_stack(&s,1);
	push_stack(&s,2);
	push_stack(&s,3);
	push_stack(&s,4);
	push_stack(&s,5);
	push_stack(&s,6);

	int num=0;
	pop_stack(&s,&num);

	traverse_stack(&s);

	clear_stack(&s);
	traverse_stack(&s);


	return 0;
}

void init_stack(PSTACK ps)
{
	ps->ptop = (PNODE)malloc(sizeof(NODE));
	if(NULL == ps->ptop){
		printf("error!\n");
		exit(-1);
	}
	else
	{
		ps->pbottom = ps->ptop;
		ps->ptop->pnext = NULL;//初始化指向的那个空栈的指针域为null
	}
}

void push_stack(PSTACK ps,int val)
{
	PNODE pnew = (PNODE)malloc(sizeof(NODE));
	//完成pnew的制作
	pnew->data = val;
	pnew->pnext = ps->ptop;
	//指向pnew;
	ps->ptop = pnew;
}

bool empty_stack(PSTACK ps)
{
	if(ps->ptop == ps->pbottom)	return true;
	return false;
}

void traverse_stack(PSTACK ps)
{
	PNODE p = ps->ptop;
	while(p != ps->pbottom){
		printf("%d ",p->data);
		p = p->pnext;
	}
	return;
}

bool pop_stack(PSTACK ps,int * pval)
{
	//出栈数据存入pval所指向的变量
	if(empty_stack(ps))	return false;

	PNODE r = ps->ptop;
	ps->ptop = r->pnext;

	free(r);
	r = NULL;
}

void clear_stack(PSTACK ps)
{
	if(empty_stack(ps))	return;

	PNODE p = ps->ptop;//指向第一个
	PNODE q = p->pnext;//指向第二个

	while(p!=ps->pbottom){
		q = p->pnext;
		free(p);
		p = q;
	}
	ps->ptop = ps->pbottom;

}

阅读更多
个人分类: acmer
所属专栏: acmer菜鸟学习工具
上一篇【菜鸟er】模板专题_幂运算快速取模
下一篇【菜鸟er】C语言数据结构_链表应用
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭