将单词插入链接列表时出错

时间:2013-08-25 11:21:49

标签: c++ linked-list

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

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;
}
}

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

2 个答案:

答案 0 :(得分:0)

while循环看起来有点奇怪,你不需要一个循环来插入一个给定search()函数的单个元素(用一个名为tail的指针代替)此外,

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

以上head == NULL永远无法评估为true,因为while条件已经过滤掉了这种可能性。

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;
    }

}

答案 1 :(得分:0)

我猜你错过了,  tail = tail-> next;刚过 tail-> next = newNode;

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