【数据结构】链栈

LinkStack.h


#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>

typedef int ElemType;
//链栈
typedef struct LinkStackNode
{	
	struct LinkStackNode* link;
	ElemType data;
}LinkStackNode;

void LinkStackInit(LinkStackNode** ppst);
void LinkStackPush(LinkStackNode** ppst,ElemType x);
void LinkStackPop(LinkStackNode** ppst);
void LinkStackShow(LinkStackNode* pst);
ElemType LinkStackTop(LinkStackNode* pst);

.
.
.
.
LinkStack.c

#include"ListStack.h"

void LinkStackInit(LinkStackNode** ppst)
{
	assert(*ppst);//等价于if(*ppst)!=NULL 则进行下面的操作
	*ppst = NULL;
}

void LinkStackPush(LinkStackNode** ppst, ElemType x)
{
	//assert(*ppst != NULL);
	LinkStackNode* newNode = (LinkStackNode*)malloc
	(sizeof(LinkStackNode));
	assert(newNode);

	//头插
	newNode->link = *ppst;
	newNode->data = x;
	*ppst = newNode;
}


void LinkStackPop(LinkStackNode** ppst)
{
	assert(*ppst);
	//没有结点
	if (*ppst != NULL)
	{
		LinkStackNode* p = *ppst;
		*ppst = p->link;
		free(p);
	}
	  
}

ElemType LinkStackTop(LinkStackNode* pst)
{
	assert(pst);
	return pst->data;
}


void LinkStackShow(LinkStackNode* pst)
{
	assert(pst);
	LinkStackNode* p = pst;

	while (p)
	{
		printf(" | %d |\n", p->data);
		p = p->link;
	}

	printf(" ----- \n");
	 
}

.
.
.
.
test.c

#include"ListStack.h"


void TestListStack()
{
	LinkStackNode* pst=NULL;	
	LinkStackInit(&pst);

	
	LinkStackPush(&pst, 1);
	LinkStackPush(&pst, 2);
	LinkStackPush(&pst, 3);
	LinkStackPush(&pst, 4);
	LinkStackPush(&pst, 5);
	LinkStackShow(pst);

	LinkStackPop(&pst);
	LinkStackPop(&pst);
	LinkStackShow(pst);

	printf("top=%d", LinkStackTop(pst));

}



int main()
{
	TestListStack();
	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值