删除双向链表中的元素时遇到问题

时间:2013-05-07 12:14:07

标签: c data-structures

我已经尝试了大约5个小时来使这段代码正常工作,代码是根据互联网研究时间编写的。 我已多次修改它,所有这些都给了我分段错误,因此这是唯一运行的版本。 发生了什么,是代码循环,并删除不仅要删除的元素,而是删除它之前的所有元素。因此,如果要删除最后一个元素,列表中的所有内容都会删除。或者,如果要删除第二个元素,第一个和第二个元素,依此类推。 它认为输入的每个名字都是出于某种原因的最高名称。

static void menu_delete_employee(void)
{
  char deletename[MAX_NAME_LENGTH+1]; 
  char namecheck[MAX_NAME_LENGTH+1]; 
  int errorcheck = 0;
  int foundit = 0;
  fprintf(stderr, "Enter the name of the employee you wish to delete\n");
  gets(deletename);
  employee_list = top;
  employee_list->name;

  do
  {
    strcpy (namecheck, employee_list->name);
    printf("namecheck = %s\n", namecheck);
    errorcheck = (strcmp (namecheck, deletename));
    printf("errorcheck = %i\n", errorcheck);

    switch (errorcheck)
    {
      case 0:
        {
          printf("This is the right name\n");
          foundit = 1;
          if (employee_list->prev == NULL)
          {
            printf("top name\n");
            top = employee_list->next;
          }
          else
          {
            if (employee_list->next == NULL) 
            {
              printf("last one\n");
              temp = employee_list->prev;
              temp-> next = NULL;
              free (employee_list);
            }
            else
            {
              printf("somewhere in the middle");
              temp = employee_list->prev;
              temp->next = employee_list->next;
              employee_list->next->prev = temp;
              free (employee_list);
            }
          }
          printf("delete successful\n");
          break;
        }
      default:
        {
          printf("not this one\n");
          errorcheck = 0;
          employee_list = employee_list->next;
          break;
        }
    }
  }
  while (foundit == 0);
  if (foundit == 0)
    printf("Name not recognised\n.");
  return;    
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

也许双重链接列表不会按照您认为的方式构建。必须首先检查这一点。

假设拓扑结构正确,此代码仍存在一些问题:

employee_list->name;(在do循环上方):这是什么?

strcpy (namecheck, employee_list->name);:你不需要复制,这只是一个简写,所以namecheck可以是(const)字符串指针。

switch (errorcheck):这只有2个武器,为什么不使用if

if (employee_list->prev == NULL) ...:您只需在此处移动top指针,但不删除顶部项目,这会导致内存泄漏。您也不要将下一个项目的prev指针设置为NULL

在“中间的某个地方”部分:你释放employee_list这是当前的位置指针。要处理的下一个项目应为temp->next,对吧?这可能是你的问题,因为你没有注意移动当前指针。此外,最好将显式名为tobedeleted的指针设置为要删除的项,确保用于沿列表迭代的指针(在您的情况下为employee_list)被适当地移动,并且*tobedeleted从双向链表中适当隔离,然后发出free(tobedeleted)命令。

employee_list = employee_list->next;:你应该检查employee_list在最后一项变成NULL,然后退出循环。否则会发生坏事。

最后的建议:你真的需要咨询好的C书...... Kernighan and Ritchie  例如。比“互联网研究”更好。