返回节点指针的功能

时间:2014-09-24 08:22:59

标签: c++ pointers object struct linked-list

大家好!我正在制作自己的链表模板,以便实践和将来使用;但是,我遇到了一个问题:

Node * LinkedList :: FindNode(int x); //用于遍历列表并返回指向包含x的指针作为其数据。

当我尝试在我的实现文件中声明它时,我不断收到Node未定义和不兼容错误的消息。

这是我的头文件:

#pragma once
using namespace std;

class LinkedList
{
private:
    struct Node 
    {   
        int data;
        Node* next = NULL;
        Node* prev = NULL;
    };

    //may need to typedef struct Node Node; in some compilers

    Node* head;  //points to first node
    Node* tail; //points to last node
    int nodeCount; //counts how many nodes in the list

public:
    LinkedList(); //constructor 
    ~LinkedList(); //destructor
    void AddToFront(int x); //adds node to the beginning of list
    void AddToEnd(int x); //adds node to the end of the list
    void AddSorted(int x); //adds node in a sorted order specified by user
    void RemoveFromFront(); //remove node from front of list; removes head
    void RemoveFromEnd(); //remove node from end of list; removes tail
    void RemoveSorted(int x); //searches for a node with data == x and removes it from list 
    bool IsInList(int x); //returns true if node with (data == x) exists in list
    Node* FindNode(int x); //returns pointer to node with (data == x) if it exists in list
    void PrintNodes(); //traverses through all nodes and prints their data
};

如果有人可以帮我定义一个返回Node指针的函数,我将非常感激!

谢谢!

1 个答案:

答案 0 :(得分:3)

由于Node是在另一个类中声明的,您是否记得在实现中引用类名时包含类名?

LinkedList::Node *LinkedList::FindNode(int x) { ... }

在类声明中,前缀不是必需的,因为声明在类中,因此Node是隐式可用的。