動態棧的實現

惠hiuj發表於2024-05-07
/********************************************************************************************************
*
*	file name:	Zqh_棧實現.c
* 	author	 :	keyword2024@163.com
* 	date	 :	2024/05/05
* 	function :	該程式實現動態棧元素的增刪改查	
*	note	 :	模板
*	
*  Copyright (c)  2023-2024   keyword2024@163.com    All right Reserved
* ******************************************************************************************************/

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

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

typedef struct Stack
{
	PNODE pTop;
	PNODE pBottom;
}STACK,*PSTACK;

PSTACK create_stack();
void push_stack(PSTACK,int);
void traverse_stack(PSTACK);
bool pop_stack(PSTACK,int *);
bool is_empty(PSTACK);
void clear_stack(PSTACK);

int main()
{	
	int data_pop;
	//建立一個空的棧,pS指標指向該棧
	PSTACK pS = create_stack();

	//向該棧中壓入資料,遍歷該棧並輸出棧中的資料
	push_stack(pS,2);
	push_stack(pS,6);
	push_stack(pS,28);
	traverse_stack(pS);	

	//從該棧中推出資料,遍歷該棧並輸出棧中的資料
	if(pop_stack(pS,&data_pop))
	   printf("pop succeed,the data poped out is:%d\n",data_pop);
	else 
   	   printf("pop failed\n");
	traverse_stack(pS);
	
	//清空棧,遍歷該棧並輸出棧中的資料
	clear_stack(pS);
	printf("data cleared!\n");
	traverse_stack(pS);

	return 0;
}

/*
建立一個空棧,並返回指向該棧的指標
*/
PSTACK create_stack()
{
	PSTACK pS = (PSTACK)malloc(sizeof(STACK));
	pS->pTop = (PNODE)malloc(sizeof(NODE));
	if(NULL==pS || NULL==pS->pTop)
	{
	   printf("malloc failed");
	   exit(-1);
	}	
	else
	{
	   pS->pBottom = pS->pTop;
	   pS->pBottom->pNext = NULL;
	}
	
	return pS;
}

/*
判斷該棧是否為空
*/
bool is_empty(PSTACK pS)
{
	if(pS->pTop == pS->pBottom)
	   return true;
    	else
	   return false;
}

/*
向pS指標指向的棧中壓入資料val
*/
void push_stack(PSTACK pS,int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	if(NULL==pNew)
	{
	   printf("malloc failed");
	   exit(-1);
	}	
	else
	{
	   pNew->data = val;
	   pNew->pNext = pS->pTop;
	   pS->pTop = pNew;
	}	
	return ;
}

/*
從棧中推出資料,並將推出的資料儲存在pData指標所指向的位置
*/
bool pop_stack(PSTACK pS,int *pData)
{
	if(is_empty(pS))
	   return false;
	else
	{
	   PNODE p = pS->pTop;
	   *pData = p->data;
	   pS->pTop = p->pNext;
	   free(p);
	   p = NULL;
	   return true;
	}
}

/*
遍歷棧,並自棧頂向棧底輸出棧中的資料
*/
void traverse_stack(PSTACK pS)
{
	PNODE pCurrent = pS->pTop; 
	printf("Now datas int the stack are:\n");
	while(pCurrent != pS->pBottom)
        {
	   printf("%d ",pCurrent->data);
	   pCurrent = pCurrent->pNext;
	}
	printf("\n");
	return ;
}

/*
清空棧,即將其還原為空棧
*/
void clear_stack(PSTACK pS)
{
	if(is_empty(pS))
	   return ;
	else
	{
	   PNODE p = pS->pTop;
	   PNODE r = NULL;
	   while(p != pS->pBottom)
	   {
	    	r = p->pNext;
		free(p);
		p = r;
	   }
	   pS->pTop = pS->pBottom;
   	}
}

相關文章