2015-04-28 35 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