2011-01-10 214 views
0

我正在開發一個通用鏈表。儘管編譯器沒有提供任何錯誤,但是在運行該程序時,它只是崩潰。我一直無法弄清楚什麼是錯誤的,但由於我正在嘗試在main中插入列表方法,問題本身就存在。下面是代碼List.h鏈接列表實現 - 程序崩潰

#include<cstdlib> 

enum Error_code 
{ 
    success, 
    overflow, 
    underflow, 
    range_error 
}; 

template<class Node_entry> 
struct Node 
{ 
    Node_entry entry; 
    Node<Node_entry> *next; 

    Node() 
    { 
     next=NULL; 
    } 

    Node(Node_entry item, Node<Node_entry> *add_on=NULL) 
    { 
     entry=item; 
     next=add_on; 
    } 
}; 

template<class List_entry> 
class List 
{ 
    public: 
    List() 
    { 
     count=0; 
     head=NULL; 
    } 

    Error_code insert(int position, const List_entry &x) 
    { 
     if(position<0 || position>count) 
      return range_error; 
     Node<List_entry> *previous, *following, *new_node; 
     if(position>0) { 
      previous=set_position(position-1); 
      following=previous->next; 
     } else { 
      following=head; 
     } 
     new_node = new Node<List_entry>(x, following); 
     if(new_node==NULL) 
      return overflow; 
     if(position==0) 
      head=new_node; 
     else 
      previous->next=new_node; 
     count++; 
     return success; 
    } 

    Error_code remove(int position, List_entry &x) 
    { 
     if(position<0 || position>count) 
      return overflow; 
     Node<List_entry> *old_node, *previous; 
     if(position==0) 
      old_node=head; 
     else { 
      previous=set_position(position-1); 
      old_node=previous->next; 
     } 
     if(old_node==NULL) 
      return underflow; 
     if(position==0) { 
      head=old_node->next; 
      delete old_node; 
     } else { 
      previous->next=old_node->next; 
      delete old_node; 
     } 
     count--; 
     return success; 
    } 

    bool empty() const 
    { 
     return count==0; 
    } 

    ~List() 
    { 
     Node<List_entry> *temp_node=head->next; 
     while(!empty()) { 
      delete head; 
      head=temp_node; 
      temp_node=head->next; 
     } 
    } 

    protected: 
    int count; 
    Node<List_entry> *head; 

    Node<List_entry> *set_position(int position)const 
    { 
     Node<List_entry> *q=head; 
     for(int i=0;i<count;i++) 
      q=q->next; 
     return q; 
    } 
}; 

的main.cpp

#include <iostream> 
#include"List.h" 
using namespace std; 
int main() 
{ 
    int i; 
    List<int> the_list; 
    the_list.insert(1, 2); 
} 

P.S我只是爲學習基礎知識,而不是現在的工作對大型設計模塊和做法。在這一點上,這隻需要工作。

+0

這不是一個很好的初步實踐,包括「代碼」到頭文件。只需將原型放入標題即可。 – ykatchou 2011-01-10 10:23:25

+0

其通用實現。如果我做了分離定義和代碼文件,它會給出錯誤。 – Cipher 2011-01-10 10:24:28

+0

你可以縮進你的代碼PLZ嗎?它實際上是不可讀的: – ykatchou 2011-01-10 10:26:24

回答

1

main功能會發生什麼事是:

  1. 建構列表;成功。
  2. 嘗試到位置1的insert,由於position>countrange_error失敗。如果您選擇返回錯誤代碼,則應始終檢查它們。
  3. 銷燬列表。這是因爲出現segfaults是headNULL當您嘗試取消對它的引用與Node<List_entry> *temp_node=head->next;
4

您在構造函數中將頭部設置爲NULL,但不要在任何函數中檢查null。在set_position中,你會盲目地嘗試迭代頭部和伴隨節點而不驗證它們實際存在。

1

只是添加到其他答案 - set_position方法有一個錯誤,它使用count而不是position