0

所以我在这里有我的链接列表结构

struct ListNode
{
    string item;
    ListNode *next;
};

ListNode *head;
ListNode *cur;
ListNode *prev;
ListNode *search();

以及我将节点添加到链接列表中的方法

inline void List::guessedWords( string guess )
{
cur = head;

while ( cur != NULL )
{
    ListNode *newNode = new ListNode;
    newNode->item = guess;

    if ( head == NULL )
    {
        newNode->next = NULL;
        head = newNode;
    }

    else
    {
        prev = search();
        newNode->next = cur;
        prev->next = newNode;
    }

    cur = newNode;
}
}

任何人都可以指出我的错误是什么?我无法添加第一个节点。
搜索功能是遍历到节点的末尾。我想要做的是继续在他的节点后面添加单词。

4

2 回答 2

0

我猜你不见了,tail = tail->next; 就在tail->next = newNode之后;

它将确保 tail 更新到最后一个节点。

于 2013-09-23T13:09:06.213 回答
0

The while loop looks a bit strange, you don't need a loop to insert a single element given the search() function (which an be replaced with a pointer called tail) Also,

cur = head;
while ( cur != NULL )
{   /* .... */
    if ( head == NULL )

the above head == NULL can never evaluate to true because the while condition already filters out that possibility.

head = tail = NULL;
inline void List::guessedWords( string guess )
{

    ListNode *newNode = new ListNode;
    newNode->item = guess;
    newNode->next = NULL;

    if ( head == NULL )
    {
        head = newNode;
        tail = newNode;
    }
    else
    {
        tail->next = newNode;
    }

}
于 2013-08-25T11:29:52.013 回答