我的链表代码中的错误

时间:2013-09-03 14:03:02

标签: c++ linked-list

我正在尝试创建一个自包含的链表。我在打印数据时遇到错误。 List.exe中0x00bf25a6处的未处理异常:0xC0000005:访问冲突读取位置0xcdcdcde5。

我尝试在Next()中使用返回类型修复它,但我无法解决它...

    void main()
    {
        // construct a list
        Element *root = new Element("Hello");

        root->Append(Element("Linked"));
        root->Append(Element("List"));      
        root->Print(0);
        root->Next()->Print(1); //This is where I get error
    }

    class Element
    {
    public:
        Element(const std::string& str)
        {
            data = str;
            link = NULL;
        }



 void Append(const Element& elem)
    {
         Element *tail = this;
    //printf("%s\n", tail->data.c_str());
    while (tail->link)
        tail = tail->link;
    tail->link = new Element(elem.data);
    }

        void Print(int n)
        {
            if(n==0)
            {
                Element *current = this;
                while (current != NULL)
                {
                    printf("%s\n", current->data.c_str());
                    current = current->link;
                }
            }
            if(n==1)
                printf("%s\n", next->data.c_str());
        }

        Element *Next()
        {
            next = this;
            if(next->link)
                return next->link;
            else
                return NULL;
        }

    public: 
        string data;
        Element *link;
        Element *next;      
    };

0 个答案:

没有答案