您的位置:首页 > 编程语言 > C语言/C++

C++实现链栈

2015-10-07 09:30 405 查看
/*
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: