栈的链式表示,即链栈。由于栈的操作是线性表操作的特例,因此链栈可以看成运算受限的单链表。其特点如下:
①链栈无栈满问题,空间可扩充;
②插入和删除仅在栈顶处执行;
③链式栈的栈顶在链头;
④适合于多栈操作。
stackList.h
#include<iostream>
class ListInt
{
public:
ListInt() { data = 0;};
int data;
ListInt *link;
};
class StackList
{
public:
StackList() { top=0; };
~StackList();
bool IsEmpty() const {return top==0;} //栈空返回1,否则返回0
void GetTop(ListInt& x); //获得栈顶元素
bool Push(const ListInt& x); //元素x入栈
bool Pop(ListInt& x); //元素出栈,并保存在x中
bool Pop(); //元素出栈
void ClearStack(); //清除栈中所有元素
void Output(); //输出栈元素
private:
ListInt *top; //指向栈顶的结点
};
stackList.cpp
#include <iostream>
#include "stackList.h"
using namespace std;
StackList::~StackList()
{
ListInt *next;
while(top)
{
next=top->link;
delete top;
top = next;
}
}
void StackList::GetTop(ListInt& x)
{
if(!top)
{
cout<<"The stack is empty!"<<endl;
return;
}
x = *top->link;
}
bool StackList::Push(const ListInt &x)
{
ListInt *listTemp = new ListInt;
*listTemp = x;
listTemp->link = top;
top = listTemp;
return true;
}
bool StackList::Pop(ListInt &x)
{
if(IsEmpty())
{
cout<<"栈为空!"<<endl;
return false;
}
x = *top;
top = x.link;
return true;
}
bool StackList::Pop()
{
if(IsEmpty())
{
cout<<"栈为空!"<<endl;
return false;
}
ListInt *x;
x = top;
top = x->link;
delete x;
return true;
}
void StackList::Output()
{
ListInt *next;
next = top;
if(IsEmpty())
{
cout<<"栈为空!"<<endl;
return;
}
while(next)
{
cout<<next->data<<" ";
next = next->link;
}
cout<<endl;
}
void StackList::ClearStack()
{
ListInt *next;
while(top)
{
next=top->link;
delete top;
top = next;
}
top = 0;
}
测试文件:stack.app
#include <iostream>
#include "stackList.h"
using namespace std;
int main()
{
StackList *stackList = new StackList();
ListInt x ;
x.data = 5;
stackList->Push(x);
x.data = 6;
stackList->Push(x);
x.data = 8;
stackList->Push(x);
x.data = 62;
stackList->Push(x);
x.data = 12;
cout<<"当前栈中元素为:"<<endl;
stackList->Output();
stackList->Pop(x);
cout<<"出栈元素:"<<x.data<<endl;
stackList->GetTop(x);
cout<<"栈顶元素:"<<x.data<<endl;
cout<<"当前栈中元素为:"<<endl;
stackList->Output();
return 0;
}
运行结果:

本文介绍了一种使用链表实现栈的数据结构方法,即链栈。详细展示了链栈的基本操作,包括入栈、出栈、获取栈顶元素等,并通过示例代码演示了如何创建和操作链栈。
1062

被折叠的 条评论
为什么被折叠?



