【问题标题】:what is wrong with this c++ linked list code?这个 c++ 链表代码有什么问题?
【发布时间】:2015-02-16 17:33:03
【问题描述】:

我正在学习 C++ 控制台应用程序课程

我试图创建一个链表

Visual Studio 刚刚给了我超过 30 个错误,尽管代码对我来说似乎非常好

你的实际错误是什么?

 #include <iostream>

using namespace std;

template <class Nodetype>
class Node{
private:
    Nodetype data;
    Node<Nodetype>*next;
    friend Linkedlist ;
};

template <class Nodetype>
class Linkedlist{
private:
    Node<Nodetype>*head;
public:
    Linkedlist();
    void insertItem(Nodetype item);
    void DeleteItem(Nodetype item);
    void MakeEmpty();
    bool FindItem(Nodetype item);
    void Display();
};
template <class Nodetype>
Linkedlist<Nodetype>::Linkedlist()
{
    head = NULL;
}

template <class Nodetype>
void Linkedlist< Nodetype >::insertItem(Nodetype item)
{
    Node< Nodetype > *location;
    location = new Node< Nodetype >();
    location->data = item;
    location->next = head;
    head = location;
}

template <class Nodetype>
void Linkedlist<Nodetype>::Display()
{
    Node<Nodetype>*current = head;
    while (current != NULL)
    {
        cout << current->data;
        current = current->next;
    }
}

template <class Nodetype>
void Linkedlist< Nodetype >::DeleteItem(Nodetype item)
{
    Node< Nodetype >* preLocation = NULL;
    Node< Nodetype >* location = head;
    if (item == location->data)
        head = location->next;
    else
    {
        do
        {
            preLocation = location;
            location = location->next;
        } while (item != location->data);
        preLocation->next = location->next;
    }
    delete location;
}

template <class Nodetype>
void Linkedlist<Nodetype>::MakeEmpty()
{
    Node<Nodetype>* tempPtr;
    while (head != NULL)
    {
        tempPtr = head;
        head = head > next;
        delete tempPtr;
    }
}

template <class Nodetype>
bool Linkedlist<Nodetype>::FindItem(Nodetype item)
{
    bool found;
    Node<Nodetype> *currentPos = head;
    found = false;
    while ((currentPos != NULL) && !found)
    {
        if (item == (currentPos->data))
            found = true;
        else
            currentPos = currentPos->next;
    }
    return found;
}

void main(){
    int x = 0;
    Linkedlist<string> L;
    L.insertItem("name1");
    L.insertItem("name2");


    cin >> x;
}

【问题讨论】:

  • 去调试吧。我相信你可以在旁边找到很多错误信息。
  • “代码看起来非常好,我确信这些编译器错误没有任何意义”。
  • “代码对我来说似乎非常好” - 一般的经验法则,每次你认为编译器错了,你就是。
  • 我知道我是这样说“对我”的,这意味着我看不出问题出在哪里,而不是指责编译器

标签: c++


【解决方案1】:

Visual Studio 刚刚给了我超过 30 个错误,尽管代码对我来说似乎非常好

不好,全是错误。

听听你的编译器。转到它告诉您有错误的行。修复它们。

例如:

     head = head > next;

这显然是错误的。修复它。

这不是有效的 C++:

friend Linkedlist ;

应该是:

template<class T> friend class LinkedList;

但你应该先声明LinkedList,然后再说它是朋友。

【讨论】:

  • 修复了“head = head > next;”没有任何改变:D,但是当首先声明 LinkedList 时,错误从 30 开始:3 我想我可以处理剩下的问题,因为你指出 :)
  • ps: "朋友链表;"很适合我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多