尝试对链接列表进行排序时出现分段错误

时间:2016-04-13 04:50:38

标签: c++ sorting linked-list segmentation-fault

每次我尝试运行这个程序时,我都会遇到分段错误。当我尝试将链表中的所有数字从最小到最大排序时,我发现它在while循环中的某个地方 -

while(marker_ptr->link()->link()!= NULL)
{
  minum = prev->link();
  temp=minum->link();
  prev->set_link(temp);
  minum->set_link(head_ptr);
  head_ptr=minum;
  marker_ptr=minum->link();
previouse_minimum(head_ptr);
    }

我不知道它有什么问题

这是大部分代码,因此您可以获得我正在使用它的上下文

node(
    const value_type& init_data = value_type( ),
    node* init_link = NULL
)
{ data_field = init_data; link_field = init_link; }

// Member functions to set the data and link fields:
    void set_data(const value_type& new_data) { data_field = new_data; }
    void set_link(node* new_link)             { link_field = new_link; }

// Constant member function to retrieve the data:
value_type data( ) const { return data_field; }

// Constant member functions to retreive the link:
    node* link( ) const          { return link_field; }

private:
value_type data_field;
node* link_field;
};

node* previouse_minimum(node*& head_ptr){
    node* cursor;
    node* minimum;
    node* prev;
    minimum=head_ptr;

    for(cursor=head_ptr; cursor != NULL; cursor=cursor->link())
      if(cursor->data() < minimum->data())
         minimum=cursor;

    cursor = head_ptr;
    prev = cursor;
   while(cursor->link() != minimum)
    {
      cursor = cursor->link();
      prev = cursor;

    }
    cout << prev->link()->data() << endl;
    return prev;

}

void sort(node*& head_ptr, node*& marker_ptr)
{
   node* print_ptr;
   node* prev = previouse_minimum(head_ptr);
   node* temp=NULL;
   node* minum;
   marker_ptr = head_ptr;

   while(marker_ptr->link()->link()!= NULL)
    {
      minum = prev->link();
      temp=minum->link();
      prev->set_link(temp);
      minum->set_link(head_ptr);
      head_ptr=minum;
      marker_ptr=minum->link();
      previouse_minimum(head_ptr);
    }
   for(print_ptr = head_ptr; print_ptr !=NULL; print_ptr = print_ptr->link())
   cout <<  print_ptr->data() << " ";

   cout << endl;

   }

0 个答案:

没有答案