栈的实现
Posted *尘封的记忆*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈的实现相关的知识,希望对你有一定的参考价值。
该程序定义了链式栈(栈的链式存储结构)的存储结构,并实现了链式栈的基本操作,例如:构造函数、拷贝构造函数和赋值运算符重载函数的实现、析构函数、判空、插入、删除、获取栈顶元素,遍历。
#include<iostream>
using namespace std;
typedef int StackElement;
struct Node
{
Node *next;
StackElement data;
Node(StackElement value, Node *link = NULL) :data(value),next(link)
{}
};
class Stack
{
public:
Stack() :myTop(NULL)
{}
Stack(const Stack& original)
{
myTop = NULL;
if (!original.empty())
{
myTop = new Node(original.Top()); //复制第一个节点
Nodeptr lastPtr = myTop; //设置指针以遍历整个栈的链表
Nodeptr origPtr =original.myTop->next;
while (origPtr != 0)
{
lastPtr->next = new Node(origPtr->data);
lastPtr = lastPtr->next;
origPtr = origPtr->next;
}
}
}
~Stack()
{
Nodeptr ptr = myTop, nextPtr;//ptr将被释放的节点,nextptr是ptr后继
while (ptr!=0)
{
nextPtr = ptr->next;
delete ptr;
ptr = nextPtr;
}
}
Stack& operator=(const Stack&rhs)
{
if (this!=&rhs)
{
this->~Stack();//销毁当前的链表
if (rhs.empty()) //空栈
myTop = NULL;
else
{
myTop = new Node(rhs.Top()); //复制第一个节点
Nodeptr lastPtr = myTop; //设置指针以遍历整个栈的链表
Nodeptr rhsPtr = rhs.myTop->next;
while (rhsPtr != 0)
{
lastPtr->next = new Node(rhsPtr->data);
lastPtr = lastPtr->next;
rhsPtr = rhsPtr->next;
}
}
}
return *this;
}
StackElement Top() const
{
if (!empty())
{
return (myTop->data);
}
else
{
cout << "The Stack is empty!" << endl;
}
}
bool empty() const
{
return myTop==0;
}
void push(const StackElement& value)
{
myTop = new Node(value, myTop);
}
void Display()
{
Nodeptr ptr;
for (ptr = myTop; ptr != 0; ptr = ptr->next)
cout << ptr->data <<" ";
cout << endl;
}
void pop()
{
if (!empty())
{
Nodeptr ptr=myTop;
myTop = myTop->next;
delete ptr;
}
else
{
cout << "Stack is empty" << endl;
}
}
private:
typedef Node* Nodeptr;
Nodeptr myTop;
};
void main()
{
Stack s;
cout<<s.empty()<<endl;
for (StackElement i = 1; i < 6; ++i)
{
s.push(i);
}
cout << s.empty() << endl;
cout << s.Top() << endl;
s.Display();
s.pop();
s.Display();
Stack s1(s);
s1.Display();
Stack s2;
s2 = s;
s2.Display();
system("pause");
}
以上是关于栈的实现的主要内容,如果未能解决你的问题,请参考以下文章