注册 登录
编程论坛 C++教室

求助!关于栈的模板类的问题

fzujj 发布于 2007-12-21 11:27, 1393 次点击
最近写了个用栈实现的程序,编译的时候栈的模板类出现了许多错误,麻烦哪位帮我瞧瞧
栈的模板类的代码:
#include<iostream>
using namespace std;
template <class T>
//栈的结点
class Node{
    public:
        friend class stack <T>;
        Node(const T&x);
    private:
        Node<T> * next;  
        T data;
};
template<class T>
Node<T>::Node(const T&x){
    date=x;
    next=0;
}
template<class T>
//栈
class stack{
private:
    int n;
    Node<t> * top;
public:
    stack();
int isempty();
T& head();
stack<T>& push(const T& x);
stack<T>& pop(const T& X);
int count();
~stack(){
    Node<t> *p;
    while(top){
        p=top->next;
        delete top;
        top=p;
    }
}
};
template <class T>
stack<T>::stack(){
    n=0;
    top=0;
}
template <class T>
int stack<T>::isempty(){
if(top)
return 1;
return o;
}
template <class T>
//返回栈顶的元素
T& stack<T>::head(){
    if(top)
        exit(1);
    return top->date;
}
template <class T>
//进栈
stack<T>& stack<T>::push(const T & x){
    Node<T> *P=new Node<T>(x);
    p->next=top;
    top=p;
    return *this;
}
template <class T>
//出栈
stack<T>& stack<T>::pop(const T & x){
    Node<T> *p;
    p=top;
    x=top->date;
    top=top->next;
    delete p;
    return *this;
}
template <class T>
//栈中元素个数
int stack<T>::count(){
    if(isempty())
        exit(1);
    Node<T> *p;
    p=top;
    while(p){
        p=p->next;
        n++;
    }
    return n;
}
10 回复
#2
wfpb2007-12-21 11:41
new出来何以为栈?
#3
fzujj2007-12-21 15:39
用指针实现栈,添加新结点不要为结点申请空间吗?
#4
中学者2007-12-21 16:46
LZ做的是链栈么???已经看到一个语法错误:
 Node<t> * top;   t 是T
#5
fzujj2007-12-21 17:08
链栈,哦,那是个错误,不过不是主要的错误
#6
中学者2007-12-21 17:21
在using 这句下面加一句:
template<class T>
class stack;
#7
中学者2007-12-21 17:25
你 有 很多语法错误,但是在VC6.0能通过,但是加上main以后就出现问题了,我也不知道为什么~
#8
aipb20072007-12-21 19:45
stack<T>

有现成的stl啊,可以看看实现代码。
#9
aipb20072007-12-21 19:46
原帖由 [bold][underline]wfpb[/underline][/bold] 于 2007-12-21 11:41 发表 [url=http://bbs.bc-cn.net/redirect.php?goto=findpost&pid=1156883&ptid=193647][/url]
new出来何以为栈?

此栈非彼栈,呵呵
#10
魔城侠客2007-12-21 19:59
1、应该把结点放在一个结构体内,这样看起来顺眼点
2、 Node这个类中的构造不要参数
3、习惯,应该把next赋值为NULL,因为是指针
4、POP中的参数不要,因为里面的x应该在里面定义,如果硬要不可,那把const去掉
5、head()这里,应该是if(!top)
#11
fzujj2007-12-21 21:40
谢谢各位,明白了不少
1