2011-01-10 213 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