通用栈实现

C++通用栈实现

#include
#include
#include
#include

// 栈中一个一个的元素 
typedef struct Node
{
	void *pdata;
	// 指向上一个结点的指针  previous next  -> pnext 
	struct Node *pnext;
}Node,*PNode;


// 栈 
typedef struct CStack
{
	// 栈中元素个数 
	int count;
	// 栈中元素大小 
	int data_size;
	// 栈顶元素 
	Node *phead;
}CStack,*PCStack;

// 判断当前栈是否为null 
bool IsEmpty(PCStack ps)
{
    return ps->phead == NULL;
}

// 将栈全部free掉 
void Destroy(PCStack ps)
{
	Node *p;
	while(ps->phead != NULL)
	{
	p = ps->phead;
	ps->phead = p->pnext;
	free(p->pdata);
	free(p);
	}
	ps->count = 0;
}


void InitStack(PCStack ps,int data_size)
{
	// assert判断条件是否返回正确,如果返回错误则报错 
	assert(ps != NULL);
	if(ps==NULL && data_size<0)
	{
		return ;
	}
	ps->count = 0;
	ps->data_size = data_size;
	ps->phead = NULL;
}

// 新建一个结点 
static Node* BuyNode(PCStack ps,void *pdata)
{
	Node *p = (Node*)malloc(sizeof(Node));
	p->pdata =(char *) malloc(ps->data_size);
	assert(p!=NULL && p->pdata!=NULL);
	char *pd = (char *)pdata;
	memcpy(p->pdata,pd,ps->data_size); 
	return p;
}

// 入栈 
bool Push(PCStack ps,void *pdata)
{
	Node *p = BuyNode(ps,pdata);
	
	p->pnext = ps->phead;
	ps->phead = p;
	ps->count++;
	
	return true;
}

//获取栈顶值,但不删除
bool GetTop(PCStack ps,void *rtval)
{
	if(IsEmpty(ps))
	{
	return false;
	}
	char *rt = (char *)rtval;
	char *tmp = (char*)ps->phead->pdata;
	memcpy(rt,tmp,ps->data_size);
	return true;
}


//获取栈顶值,并且删除
bool Pop(PCStack ps,void *rtval)
{
	if(IsEmpty(ps))
	{
		return false;
	}
	Node *p = ps->phead;
	char *rt = (char *)rtval;
	char *tmp = (char*)p->pdata;
	memcpy(rt,tmp,ps->data_size);
	ps->phead = p->pnext;
	free(p->pdata);
	free(p);
	ps->count--;
	return true;
}


int main()
{
	// 创建一个新的栈 
	CStack ss; 
	// 初始化栈  且栈的元素大小为 char*  
	InitStack(&ss,sizeof(char*));
	char *p[8] = {"123","1234","12345","abc","abcd","xyz","123abcd","123abcdxyz"};
	int i;
	// 用户接受从栈顶取出的元素 
	char* ptmp;
	for(i=0 ; i<8 ; i++)
	{
		// 总共定义了8个元素,8个元素依次入栈 
		Push(&ss,(void*)&p[i]);
	}
		
	while(!IsEmpty(&ss))
	{
		GetTop(&ss,(void*)&ptmp);
		printf("%s\n",ptmp);
		Pop(&ss,(void*)&ptmp);
	}
	Destroy(&ss); 
	
	return 0;
}


你可能感兴趣的:(程序设计范式,c++,数据结构,算法)