我正在尝试用 C++ 为一个名为 List 的自定义列表类编写一个方法。它是一个由节点组成的链表,节点是各种项目。对于该方法,我希望它返回一个指向节点的指针,但会收到一个错误消息,指出“‘节点’没有命名类型。” 请注意, sort() 方法仍在进行中,我正在等待 setMyNext() 。
template<class Item>
class List {
public:
List();
List(const List& original);
virtual ~List();
void sort();
List& operator=(const List& original);
bool operator==(const List& original)const;
bool operator!=(const List& l2) const;
private:
void print()const;
unsigned mySize;
struct Node{
Node();
Node(Item item, Node * next);
~Node();
void print()const;
Node * setMyNext(Node * newNext);
Item myItem;
Node * myNext;
};
Node * myFirst;
Node * myLast;
friend class ListTester;
};
template<class Item>
List<Item>::List() {
myFirst=NULL;
myLast=NULL;
mySize=0;
}
template<class Item>
List<Item>::List(const List& original){
myFirst=myLast=NULL;
mySize=0;
if(original.getSize()>0){
Node * oPtr = original.myFirst;
while(oPtr!=NULL){
append(oPtr->myItem);
oPtr=oPtr->myNext;
}
}
}
template<class Item>
List<Item>::Node::Node(){
myItem=0;
myNext=NULL;
}
template<class Item>
List<Item>::Node::Node(Item item, Node * next){
myItem=item;
myNext= next;
}
template<class Item>
List<Item>::~List() {
// cout<<"Deleting List..."<<endl;
delete myFirst;
myFirst=myLast=NULL;
mySize=0;
}
template<class Item>
void List<Item>::sort(){
//get my first 2 items
if(mySize<2)
return;
Node * compareEarly=myFirst;
Node * compareLate=myFirst->myNext;
//compare
if(compareEarly->myItem > compareLate->myItem){
//If 2<1, set 0's next pointer to 2, set 2's next to 1, set 1's next to 3
cout<<"big"<<endl;
}
//This needs a set previous pointer and set next item's pointer
//increment
}
template<class Item>
Node * List<Item>::Node::setMyNext(Node * newNext){
myNext=newNext;
}