排序双向链表时出现运行时错误

时间:2015-04-28 16:39:40

标签: c sorting

我编写了一个程序,可以创建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;
                       }
                }

       }

}

1 个答案:

答案 0 :(得分:1)

您从insertion_sort()(但之前没有)收到运行时错误的原因是您忘记设置链接列表的prev字段。所以它实际上是一个单链表,而简单的解析list_tables()也可以。但是在insertion_sort()中,您开始使用未初始化的prev指针,从而导致崩溃。