链栈基本运算(实验题3.2)

//
//实现链栈各种基本运算
//2013-10-14 22:46
//

typedef int ElemType;

typedef struct linknode
{
	ElemType data;
	struct linknode* next;
}LiStack;

void InitStack(LiStack* &s);

void ClearStack(LiStack* &s);
 
int StackLength(LiStack* s);
 
int StackEmpty(LiStack* s);

void Push(LiStack* &s,ElemType data);  //进栈

int Pop(LiStack* &s, ElemType& data);  //出栈

int GetTop(LiStack *s,ElemType& data);  //栈顶元素

void DispStack(LiStack* s);

 


#include "LiStack.h"
#include 
#include 

void InitStack( LiStack* &s )
{
	s = (LiStack*)malloc(sizeof(LiStack));
	s->next = NULL;
}

void ClearStack( LiStack* &s )
{
	LiStack* p = s,*q = s->next;
	while(q != NULL)
	{
		free(p);
		p = q;
		q = q->next;
	}
}

int StackLength( LiStack* s )
{
	int nLength = 0;
	LiStack*q = s->next;
	while(q != NULL)
	{
		nLength ++;
		q = q->next;
	}
	return nLength;
}

int StackEmpty( LiStack* s )
{
	return s->next == NULL;
}

void Push( LiStack* &s,ElemType data )
{
	LiStack* p = (LiStack*)malloc(sizeof(LiStack));
	p->data = data;

	p->next = s->next;
	s->next = p;
}

int Pop( LiStack* &s, ElemType& data )
{
	if (s->next == NULL)
	{
		return 0;
	}
	
	LiStack* q=s->next;

	data = q->data;

	s->next = q->next;

	free(q);
	return 1;
}

int GetTop( LiStack *s,ElemType& data )
{
	if (s->next == NULL)
	{
		return 0;
	}
	data = s->next->data;
}

void DispStack( LiStack* s )
{
	LiStack*q = s->next;
	while(q != NULL)
	{
		printf("%d,",q->data);
		q = q->next;
	}
	printf("\n");
}


 

 

#include "LiStack.h"

int main()
{
	LiStack*s;
	InitStack(s);

	Push(s,1);

	DispStack(s);

	Push(s,2);

	DispStack(s);

	Push(s,3);

	DispStack(s);

	Push(s,4);

	DispStack(s);

	ElemType e;

	Pop(s,e);

	DispStack(s);

	return 0;
}


 

你可能感兴趣的:(算法学习,C++学习,基础概念)