栈的链式实现方法

/************************************************************************/
/*					         栈的链式存储                               */
/************************************************************************/
#include <STDIO.H>
#include <STDLIB.H>





#define STACK_INIT_SIZE 100//栈的初始大小


#define _OK 1
#define _ERROR 0



typedef int SELemType;
typedef int Status;

struct Node;
typedef struct Node*  PTNode;




//链表节点
struct Node
{
	PTNode next;
	SELemType data;
};


/*
	栈的数据抽象
*/
typedef struct
{
	PTNode top;//栈顶指针,指向栈顶元素的下一个内存空间
	int stacksize;//栈的大小

}LkStack;



//初始化栈
void InitStack(LkStack &L)
{
	L.top = (PTNode)malloc(sizeof(Node));
	L.top->data=NULL;
	L.top->next=NULL;
	L.stacksize = 0;
}


/*判断栈中的元素是否为空*/
bool IsEmpty(LkStack L)
{
	if(L.top->next==NULL)
		return true;
	return false;
}



/*入栈操作*/
Status Push(LkStack &L,SELemType e)
{
	PTNode newElement = (PTNode)malloc(sizeof(Node));
	if (newElement==NULL)
		return _ERROR;

	//插入操作
	newElement->data=e;
	newElement->next=L.top->next;
	L.top->next=newElement;

	L.stacksize++;
	return _OK;

}



/*出栈操作*/
Status Pop(LkStack &L,SELemType &e)
{
	if(IsEmpty(L))
		return _ERROR;//表明栈已经空

	//出栈
	PTNode temp = L.top->next;
	L.top->next=temp->next;
	e = temp->data;

	free(temp);//释放空间
	L.stacksize--;
	return _OK;
}


/*取栈顶元素*/
Status GetTop(LkStack &L,SELemType &e)
{
	if(!IsEmpty(L))//如果栈不为空
		e=L.top->next->data;
	return _OK;
}



int GetStackSize(LkStack L)
{
	return L.stacksize;
}



/*打印栈中的元素*/
void PrintStack(LkStack L)
{
	PTNode temp = L.top;
	while(temp->next!=NULL)
	{
		printf("%d \n",temp->next->data);
		temp=temp->next;
	}
}




void main()
{
	//初始化一个栈
	LkStack lkstack;
	InitStack(lkstack);
	

	//向栈中压入元素
	Push(lkstack,0);
	Push(lkstack,1);
	Push(lkstack,2);
	Push(lkstack,3);
	Push(lkstack,4);
	Push(lkstack,5);
	//打印栈中的数据
	PrintStack(lkstack);



	SELemType e;
	Pop(lkstack,e);
	printf("弹出%d\n",e);

	Pop(lkstack,e);
	printf("弹出%d\n",e);

	//打印栈中的数据
	PrintStack(lkstack);
	printf("size is %d\n",lkstack.stacksize);

}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值