2013-08-25 28 views
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; 
} 
} 

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

回答

0

while循环看起来有点奇怪,你并不需要一个循环插入单个元素给出的search()功能(其中有一个叫tail指针来代替)。另外,

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

以上head == NULL永远不会评估为真,因为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; 
    } 

} 
+0

如果head == NULL错误,我将如何检查我的头是否为NULL或不插入第一个元素。 –

+0

你在while条件下检查它。你同意'head == NULL'不能评估为真? – perreal

+0

我已经省略了while循环。是的,while循环听起来不正确。不知道我的大脑在想什么。问题依旧,我无法插入第一个节点。那么,如果head == NULL不能成立,我的条件是什么?对不起,愚蠢的问题,我是新来的链接列表,并有很短的时间学习。 –

0

我猜你缺少, 尾= tail->未来;刚刚在 tail-> next = newNode;

它会确保尾部更新到最后一个节点。