【发布时间】:2021-06-09 10:09:12
【问题描述】:
我正在尝试使用 C++ 中的链表创建简单的堆栈。突然我遇到了(我认为)与模板有关的问题。我缺乏这种结构的知识,这就是为什么我试图创造一些东西并用它来学习。
我的问题是node * top; 我应该改变什么?任何想法?
我的代码是:
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename T>
class node {
public:
T object;
node * next;
};
node *top = NULL;
template<typename T>
class Stack{
public:
void push(T obj);
void pop();
void display(ostream & out) const;
};
void Stack :: push(T obj){
node * tempNode = new node;
tempNode->object = obj;
tempNode->next = top;
top = tempNode;
}
void Stack :: display(ostream & out) const{
if(top == NULL){
cout << "Stack is Empty"<<endl;
return;
}
else{
node *temp = top;
while(temp!=NULL){
cout << "Here is your elements :"<<"\n";
cout << temp->object<<endl;
temp = temp->next;
}
cout <<endl;
}
}
void Stack :: pop(){
if (top = NULL){
cout << "List is Empty"<<endl;
return;
}
cout << "Your object: "<<top->object << " is removed"<<endl;
top = top->next;
}
ostream & operator << (ostream & out, const Stack & s){
s.display(out);
return out;
}
【问题讨论】:
-
请在问题中包含编译器错误消息。
-
无意冒犯,但一般来说,不建议猜测 c++ 语法。猜测模板的语法几乎是不可能的
-
请包括样本输入和输出(预期和当前);显示的任何错误。阅读how to ask a good question
-
node是模板,每次使用都必须使用<>指定模板参数。在某些情况下(从 C++17 开始)编译器可以推断模板参数,但在任何地方添加<T>会更容易。
标签: c++ templates linked-list stack nodes