C++实现链栈

/*
 * LkStack.h
 *
 *  Created on: Oct 7, 2015
 *      Author: chris
 */

#ifndef LKSTACK_H_
#define LKSTACK_H_


typedef int ElemType;

struct LSNode{
	ElemType data;
	LSNode * next;
};

struct LkStack{
	LSNode * top;
};

bool LkStackCreate(LkStack & stk);
void LkStackDestroy(LkStack & stk);

void LkStackClear(LkStack stk);
int  LkStackLength(LkStack stk);
bool LkStackEmpty(LkStack stk);

bool LkStackPush(LkStack stk, ElemType e);
bool LkStackTop(LkStack stk, ElemType& e);
bool LkStackPop(LkStack stk);

void LkStackDisplay(LkStack stk);

#endif /* LKSTACK_H_ */



/*
 * LkStack.cpp
 *
 *  Created on: Oct 7, 2015
 *      Author: chris
 */


#include "LkStack.h"
#include <iostream>

using namespace std;

bool LkStackCreate(LkStack & stk)
{
	stk.top = new LSNode;
	if(!stk.top) return false;

	stk.top->next = NULL;
	return true;
}

void LkStackDestroy(LkStack & stk)
{
	LSNode * pcur;
	while(stk.top) {
		pcur = stk.top;
		stk.top = stk.top->next;
		delete pcur;
	}
}

void LkStackClear(LkStack stk)
{
	LSNode * sub = stk.top->next, *pcur;
	while(sub) {
		pcur = sub;
		sub = sub->next;
		delete pcur;
	}
	stk.top->next = NULL;
}

int  LkStackLength(LkStack stk)
{
	LSNode *pcur = stk.top->next;
	int cnt = 0;
	while(pcur) {
		++cnt;
		pcur = pcur->next;
	}
	return cnt;
}

bool LkStackEmpty(LkStack stk)
{
	return stk.top->next == NULL;
}

bool LkStackPush(LkStack stk, ElemType e)
{
	LSNode * pcur = new LSNode;
	if(!pcur) return false;
	pcur->data = e;

	pcur->next = stk.top->next;
	stk.top->next = pcur;
	return true;
}

bool LkStackTop(LkStack stk, ElemType& e)
{
	if(stk.top->next == NULL) return false;

	e = stk.top->next->data;
	return true;
}

bool LkStackPop(LkStack stk)
{
	if(stk.top->next == NULL) return false;

	LSNode * pcur = stk.top->next;
	stk.top->next = pcur->next;
	delete pcur;
	return true;
}


void LkStackDisplay(LkStack stk)
{
	LSNode * pcur = stk.top->next;
	while(pcur) {
		cout << pcur->data << " ";
		pcur = pcur->next;
	}
	cout << endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值