您的位置:首页 > 其它

使用链表实现堆栈

2015-02-05 15:26 69 查看
#include <iostream>
using namespace std;

/***********************************/
/*
栈的链式存储结构实际上是一个单链表,叫链栈
插入和删除操作只能在链栈的栈顶进行
*/
/***********************************/

#define MaxSize 100

typedef struct Node
{
int data;
struct Node *next;
}*pLinkStack, nLinkStack;

//链表初始化,创建一个有头结点的链表
pLinkStack CreateLinkStack()
{
pLinkStack s;
s = new nLinkStack;
s->next = NULL;
return s;
}

int IsEmptyLinkStack(pLinkStack s)
{
//判断堆栈s是否为空,若为空则返回1,否则返回0
return (s->next == NULL);
}

void PushLinkStack(int item, pLinkStack s)
{
//将元素item压入堆栈s
pLinkStack tempCell;
tempCell = new nLinkStack;
tempCell->data = item;
tempCell->next = s->next;
s->next = tempCell;    //由于头结点的存在
}

int PopLinkStack(pLinkStack pS)
{
//删除并返回堆栈s的栈顶元素
pLinkStack firstCell;
int topElem;
if ( IsEmptyLinkStack(pS) )
{
cout << "LinkStack is empty!" << endl;
return NULL;
}
else
{
firstCell = pS->next;
pS->next = firstCell->next;
topElem = firstCell->data;
delete firstCell;
return topElem;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: