栈的链式存储结构(C语言,传地址版)

#include 
#include 
#include 

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

typedef struct Stack
{
	PNODE pTop;
	PNODE pBottom;
} STACK, * PSTACK;
//PSTACK等价于struct Stack * S ,*S里面有Top和Bottom
//STACK等价于struct Stack S ,S里面有Top和Bottom


void initStack(PSTACK S);			//初始化 
void pushStack(PSTACK S);			//进栈一个节点 
void traverse_Stack(PSTACK S);		//遍历 
bool pop(PSTACK pS,int * val);		//出栈元素 
bool empty(PSTACK pS);				//判空 
void clear(PSTACK pS);				//清空 
	//|	pTop	|
	//|	pNODE	|
	//|	pNODE	|	示意图 
	//|	pNODE	|
	//|	pNODE	|
	//|	pBottom	|
//—————— 
int main(void)
{
	int val;
	PSTACK pS;               //PSTACK等价于struct Stack* ,*S里面有Top和Bottom
//	STACK  S;
	
	initStack(pS);
	pushStack(pS);
	pushStack(pS);
	traverse_Stack(pS); 
		traverse_Stack(pS); 
	if(pop(pS,&val)){
		printf("出栈了%d\n",val);
	}
	traverse_Stack(pS);
	clear(pS);
	traverse_Stack(pS);
	
	return 0;
}
//-------------------------------------------------------------------------------



void initStack(PSTACK pS)
{
	pS=(PSTACK)malloc(sizeof(STACK));
	pS->pTop=NULL;
	if(pS==NULL){
		printf("动态内存分配失败!\n");
		//exit(-1);
	}else{
		printf("success 666\n");
	}
	
	pS->pBottom=pS->pTop;
	pS->pBottom->pNext=NULL;				//pS->Top->pNext=NULL
	return ;
}

void pushStack(PSTACK pS)
{
	int val;
	printf("请输入入栈值:"); 
	scanf("%d",&val);
	PNODE pNew=(PNODE)malloc(sizeof(NODE));	//分配一个新节点 
	pNew->pNext=NULL;
	pNew->data=val;
	
	pNew->pNext=pS->pTop;
	pS->pTop=pNew;
}

void traverse_Stack(PSTACK pS)
{
	PNODE p=pS->pTop;						//不用个新指针,遍历完就不能二次遍历了,头尾指到一起 
	if(p==pS->pBottom)
	{
		printf("空栈无法遍历\n");
		exit(-1);
	}
	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 * val)
{
	if(empty(pS)){
		return false;
	}else{
		*val=pS->pTop->data;
		PNODE p=(*pS).pTop;
		pS->pTop=p->pNext;
		free(p);
		p=NULL;
	}
	return true;
}

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

你可能感兴趣的:(DS复习,链表,数据结构,c语言,c++,算法)