链式存储的栈称为链栈,结构如下图:
链栈无满栈问题,空间可扩充,但有栈空问题,栈空的条件为top->next==NULL。进栈与入栈仅在栈顶进行,链式栈的栈顶在栈表头。链栈的定义如下:
struct StackNode {
int data; //结点数据
StackNode *next; //结点链指针
};
class Stack
{
StackNode *top; //栈顶指针
public:
Stack() { top=new StackNode; top -> next = NULL; } //创建头结点
~Stack() { delete top; }
void Push(int item); //入栈
int Pop(); //出栈
int GetTop(); //获取栈顶元素
void Clear(); //清空栈
bool IsEmpty() { return top->next == NULL; } //判断栈是否为空
void Transform(long N, int d); //数制转换
};
类中具体的算法实现如下:
//入栈操作
void Stack::Push(int item)
{
StackNode *p; //新建一结点
p = new StackNode;
p->data = item;
p->next = top->next;
top->next = p;
}
//出栈操作
int Stack::Pop()
{
StackNode *p;
if (top->next!=NULL)
{
p = top->next;
int retvalue = p->data; //暂存栈顶数据
top->next = p->next; //修改栈顶指针
delete p;
return retvalue; //释放,返回数据
}else
{
cout<<"the stack is empty!"<<endl;
exit(0);
}
}
//获取栈顶元素操作
int Stack::GetTop()
{
if (top->next!=NULL)
{
return top->next->data;
}else
{
cout<<"the stack is empty!"<<endl;
exit(0);
}
}
void Stack::Clear()
{
StackNode *p;
while (top->next!=NULL)
{
p = top->next;
top->next = p->next; //修改栈顶指针
delete p;
}
}
栈的应用–数制转换(十进制转d进制):
void Stack::Transform(long N, int d)
{
Stack s;
cout<<N;
while (N!=0)
{
int k = N%d;
s.Push(k);
N = N/d;
}
cout<<"的"<<d<<"进制数为:";
while (!s.IsEmpty())
{
cout<<s.Pop();
}
cout<<endl;
}
在主函数进行具体的数据操作:
int main() {
Stack stack;
stack.Push(12);
stack.Push(23);
stack.Pop();
int t = stack.GetTop();
bool b = stack.IsEmpty();
cout<<b<<endl;
cout<<t<<endl;
stack.Transform(4587,8); //转八进制
return 0;
}