C ++链接列表搜索错误:STATUS_ACCESS_VIOLATION

时间:2012-02-20 09:28:24

标签: c++ list linked-list

我正在编写一个添加,删除和显示节点(双重链接)及其组件的程序,但每当我尝试检索节点并显示它的组件时,我都会收到此错误:

 2 [main] a 4640 exception::handle: Exception: STATUS_ACCESS_VIOLATION

2875 [main] 4640 open_stackdumpfile:将堆栈跟踪转储到a.exe.stackdump

我已将其缩小到我的.h文件中的搜索功能,该搜索功能应该搜索链接列表中是否有正在搜索的帐号的节点。该函数返回其前面的节点或“上一个”节点。

这是我的搜索功能:

bool searchListByAcctNum (int searchKey, nodePtr *prevOut)
   {
      bool found = false;
      nodePtr p = headNum;
      nodePtr prev = NULL;
      while (p != NULL)
      {
         if (p->acctNum < searchKey)
         {
            prev = p;
            p = p->nextNum;
         }
         else
         {
            if (p->acctNum == searchKey)
               found = true;
            p = NULL;
         }
      }
      *prevOut = prev;
      return found;

如果有人可以帮助我,我会很感激!

1 个答案:

答案 0 :(得分:0)

看起来您的列表可能已损坏,或者您传递给前一节点的指针无效,因为该代码看起来没问题。但是,在我看来,它可以用更简单的方式编写:

bool searchListByAcctNum (int searchKey, nodePtr *prevOut) {
    /// Start at beginning of list, use pointer variable to hold previous.

    nodePtr p = headNum;

    *prevOut = = NULL;

    // Process entire list, will exit early if need be.

    while (p != NULL) {
        // If past it, just return false, caller should ignore prevOut.

        if (p->acctNum > searchKey)
            return false;

        // If equal, return true, prevOut holds previous or NULL if found at start.

        if (p->acctNum == searchKey) {
            return true;

        // Save previous and advance to next.

        *prevOut = p;
        p = p->next;
    }

    // Reached end of list without finding, caller should ignore prevOut.

    return false;
}