链表类的模板代码已经在链式队列((15条消息) c++面向对象之链式队列_沐由霂始的博客-CSDN博客)中给出,这里不再赘述。
一.用链表实现栈
template<class T>
class cStack
{ cNode<T> *front;
int count;
public:
cStack()
{
front = NULL;
count = 0;
}
~cStack()
{
clear();
}
void push(T x)
{
cNode<T> *p = new cNode<T>(x);
p->next = front;
front = p;
count++;
}
void pop()
{
cNode<T> *p = front;
if(p)
{
count--;
front = front->next;
delete p;
}
}
T top()
{
return front->data;
}
bool empty()
{
return(!count);
}
void clear()
{
cNode<T> *p = front;
while(p)
{
cNode<T> *t = p;
p = p->next;
delete t;
}
count = 0;
}
T size()
{
return count;
}
};
1.对于栈来说,其本身只需要关注栈顶,所以只需要一个节点指向栈顶即可
2.同样需要有cNode<T> *p = front;创建新节点,便于实现操作。
二.测试
int main()
{
cStack<int> st;
for(int i=1; i<=5; i++) st.push(i);
while(!st.empty())
{
cout<<st.top()<<endl;
st.pop();
}
cout<<endl;
for(int i=1; i<=5; i++) st.push(i);
while(!st.empty())
{
cout<<st.top()<<endl;
st.pop();
}
cout<<endl;
return 0;
}
测试结果为:
三.关于用链表实现栈、队列等数据结构的看法
1.首先,与数组相比,链表的创建会复杂一些,但其功能实现上却比数组要强大得多,所以,链式存储本身也会给运行空间带来更高效的使用。
2.对于面向对象应用而言,链表会作为更为普遍的方式来实现更多的数据结构。
(以上是暂时的思考,一定有考虑不周之处,有错希望大家直接指出)