2010-07-01 38 views
-3

當只剩下一個節點(我有其他功能添加節點)時,void del_begin()怎麼會崩潰?C++中的鏈接列表(pt。2)

#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; 
} 
+6

您沒有向我們展示'del_begin()'的代碼...... – 2010-07-01 22:46:15

+4

Uhm,C++在哪裏?除了cout,這可能也是C. – 2010-07-01 22:50:58

+0

list <>或slist <>可能會更好地爲您服務。 – 2010-07-01 22:58:22

回答

1

你沒有表現出我們del_begin()的代碼,但你del_end()在你提及的情況下的一個錯誤(單節點列表)。

如果你只有一個節點,你while循環將不會執行,而當你站上罰球線temp2將是未初始化:

temp2->nxt = NULL; 

崩潰!

+0

我該如何解決它? – danutenshu 2010-07-01 23:05:45

+1

@danutenshu:您改爲使用庫列表類來修復它。有沒有理由讓你不得不推出自己的? – 2010-07-01 23:10:26

+0

我被分配製作自己的鏈接列表。你能解釋更多嗎?我沒有看到 – danutenshu 2010-07-01 23:19:36

0

如果你只有一個節點,while循環將不會執行,並TEMP2將未初始化

start_ptr &目前沒有適當重置刪除。

這不是線程安全的(以各種方式),但是例如在從列表中刪除它之前刪除下一個項目。