数据结构笔记之栈

线性结构的两种常见应用之一 栈
定义
一种可以实现“先进后出”的存储结构
栈类似于箱子
分类
静态栈
动态栈
算法
出栈
压栈
应用
函数调用
中断
表达式求值
内存分配
缓冲处理

迷宫

实例

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

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

typedef struct Stack
{
	PNODE pTop;			//顶部		栈外
	PNODE pBottom;		//底部
}STACK, * PSTACK;
	
void init(PSTACK pS);
void push(PSTACK pS,int val);
void traverse(PSTACK pS);
bool pop(PSTACK pS, int * pVal);
void clear(PSTACK pS);
bool empty(PSTACK pS);
int main()
{
	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);
	traverse(&S);

	return 0;
}

void init(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;
	}
}




void push(PSTACK pS,int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));

	pNew->data = val;
	pNew->pNext = pS->pTop;	//指向pTop
	pS->pTop = pNew;

	return;
}

void traverse(PSTACK pS)
{
	PNODE p = pS->pTop;

	while(p != pS->pBottom)
	{
		printf("%d ", p->data);
		//printf("1 ");
		p = p->pNext;
	}
	printf("\n");

	return;
}

bool empty(PSTACK pS)
{
	if(pS->pTop == pS->pBottom)
		return true;
	else
		return false;
}

//出栈
bool pop(PSTACK pS, int * pVal)
{
	

	if(empty(pS))		//pS本身存放的S的地址
	{
		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))		//pS本身存放的S的地址
	{
		return;
	}
	else
	{
		PNODE p = pS->pTop;
		PNODE q = p->pNext;
		while( p != pS->pBottom)
		{
			q = p->pNext;
			free(p);
			p = q;
		}
		pS->pTop = pS->pBottom;
	}
}


你可能感兴趣的:(数据结构,代码,栈)