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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章