2015-04-28 37 views
0

我写了一个程序,创建了12个具有随机容量的表。我想通过插入来对这个双向链表进行排序。虽然代码编译时没有错误,但我得到了运行时错误。我不知道为什么。有没有人可以帮助我?排序双向链表时的运行时错误

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <math.h> 
#include <time.h> 

#define MAX 12 

struct Table { 
     int capacity; 
     struct Table *next; 
     struct Table *prev; 
}; 

typedef void (*table_func_pnt) (struct Table *table); 
struct Table *add_random_number(struct Table *head); 
void insertion_sort(struct Table **head); 

void list_tables(struct Table *head, table_func_pnt func); 
void print_capacity(struct Table *table); 

int main(int argc, char **argv) 
{ 
     srand(time(0)); 

     struct Table *list = NULL; 

    for(int i = 0; i<MAX; ++i){ 
      list = add_random_number(list); 
    } 

    list_tables(list,print_capacity); 
    printf("\n"); 


    insertion_sort(&list); 


    list_tables(list,print_capacity); 

    return EXIT_SUCCESS; 

} 

struct Table *add_random_number(struct Table *head){ 

     struct Table *table = malloc(sizeof(struct Table)); 
     table->capacity = 2 + rand() % 10; 
     table->next = head; 

     return table; 
} 

void list_tables(struct Table *head, table_func_pnt func) 
{ 
     while(head){ 
      func(head); 
      head = head->next; 
     } 
} 

void print_capacity(struct Table *table) 
{ 
     printf("%d ",table->capacity); 
} 

void insertion_sort(struct Table **head) 
{ 
     int n; 

     struct Table *curr; 
     curr = *head; 

     if(curr->next == NULL) 
      return; 

     struct Table *ptr; 
     struct Table *temp; 
     curr = curr->next; 

     while(curr != NULL){ 

       n = 0; 
       ptr = curr; 
       temp = curr->prev; 
       curr = curr->next; 

       while(temp != NULL && temp->capacity > ptr->capacity){ 
         n++ ; 
         temp = temp->prev; 
       }if(n){ 
         ptr->prev->next = ptr->next; 
         if(ptr->next != NULL) 
         ptr->next->prev = ptr->prev; 

         if(temp == NULL){ 
          temp = *head; 
          ptr->prev = NULL; 
          ptr->next = temp; 
          ptr->next->prev =ptr; 
          *head = ptr; 
         }else{ 
          temp = temp->next; 
          temp->prev->next = ptr; 
          ptr->prev = temp->prev; 
          temp->prev = ptr; 
          ptr->next = temp; 
         } 
       } 

     } 

} 
+0

尝试在调试器中运行,找到发生崩溃的位置。 –

+0

如果你想要一个双向链表,你需要类似'if(head!= NULL){head-> prev = table;}'在函数add_random_number()中'' – francis

+0

你是对的@francis – Rinzler

回答

1

的原因,你从获得运行时错误insertion_sort()(而不是之前)是因为你忘记设置链表的prev领域。所以它实际上是一个单链表,简单的解析list_tables()的作品。但在insertion_sort()你开始使用未初始化的prev指针,导致崩溃。

+0

谢谢!@WheaherVane – Rinzler

+0

@Rinzler - 另一种方法是只使用下一个指针的排序,然后排序完成后,遍历排序列表以设置先前的指针。我不确定这是否会显着加快或值得付出努力。如果速度是一个问题(非常大的列表),那么自下而上的合并排序会快得多。 – rcgldr