C ++中的链接列表(第2页)

时间:2010-07-01 22:45:05

标签: c++ linked-list

当只剩下一个节点时,void del_begin()如何崩溃(我还有其他添加节点的功能)?

 #include <iostream>
 using namesspace std;

 node *start_ptr = NULL;
 node *current;
 int option = 0;
 void del_end()
 {
     node *temp, *temp2;
     temp = start_ptr;
     if (start_ptr == NULL)
         cout << "There are no nodes" << endl;
     else
     {
         while (temp->nxt != NULL)
         {
            temp2 = temp;
            temp = temp->nxt;
         }
         delete temp;
         temp2->nxt = NULL;
     }
 }
 void display()
 {
     node *temp;
     temp = start_ptr;
     cout << endl;
     if (temp == NULL)
         cout << "There are no nodes to display" << endl;
     else
     {
         while(temp != NULL)
         {
        cout << temp->name << ", " << temp->profession << ", " << temp->age;
        if (temp == current)
            cout << "***";
        cout << endl;
        temp = temp->nxt;
        }
        cout << endl;
     }
 }

 int main()
 {
     start_ptr = NULL;
     int option;
      do
     {
         display();
         cout << "0 for EXIT" << endl;
         cout << "1 to ADD TO END" << endl;
         cout << "2 to ADD TO BEGINNING" << endl;
         cout << "3 to DELETE LAST" << endl;
         cout << "4 to DELETE BEGINNING" << endl;
         cout << ">>";
         cin >> option;
         switch (option)
         {
         case 1 : add_end(); break;
         case 2 : add_begin(); break;
         case 3 : del_end(); break;
         case 4 : del_begin(); break;
         }
     }
     while (option != 0);
     return 0;
 }

2 个答案:

答案 0 :(得分:1)

您没有向我们展示del_begin()的代码,但您提到的del_end()有一个错误(单节点列表)。

如果您只有一个节点,那么while循环将永远不会执行,并且当您到达该行时temp2将被取消初始化:

 temp2->nxt = NULL;

崩溃!

答案 1 :(得分:0)

如果你只有一个节点,你的while循环将永远不会执行,temp2将是未初始化的

start_ptr&amp;删除时不会正确重置当前电流。

这不是线程安全的(以各种方式),但是例如,在从列表中删除之前删除下一个项目。