链栈的相关操作

/*链栈不需要设置头结点*/
#include<iostream>
typedef struct StackNode
{ 
	char data;
	struct StackNode *next;
}StackNode, *LinkStack;  

/*取栈顶元素, 只取元素,栈顶指针不变*/
int GetTop(LinkStack *top, char *e)
{
	if(*top == NULL)   //判断栈空
		return -1;
	
	*e = (*top)->data;
	return 0;
}

/*入栈操作*/
int Push(LinkStack *top, char e)
{
	LinkStack p;
	p = new StackNode;
	p->data = e;
	p->next = *top;
	*top = p;

	return 0;
}

/*出栈操作*/
int Pop(LinkStack *top, char *e)
{
	LinkStack p;
	if(*top == NULL)   //判断栈空
		return -1;

	*e = (*top)->data;
	p = *top;
	*top = (*top)->next;
	delete p;
	return 0;
}
/*清空链栈*/
void ClearLinkStack(LinkStack *top)
{
	LinkStack p;

	while(*top)
	{
		p = *top;
		*top = (*top)->next;
		delete p;
	}
}

int main()
{
	LinkStack S = NULL;  //初始化链栈S,不设头结点,S为头指针
	char e;

	Push(&S, 'U');
	Push(&S, ' ');
	Push(&S, 'e');
	Push(&S, 'v');
	Push(&S, 'o');
	Push(&S, 'L');
	Push(&S, ' ');
	Push(&S, 'I');

	LinkStack p = S;
	while(p)   //遍历链栈,从栈顶至栈底输出
	{
		std::cout<<p->data;
		p = p->next;
	}
	GetTop(&S, &e);
	std::cout<<e;

	for(int i=0; i<8; i++)
	{
		Pop(&S, &e);
		std::cout<<e;
	}
	return 0;
}

你可能感兴趣的:(struct,null)