首页 > 解决方案 > Linked LIst 排序和分段错误

问题描述

我目前正在制定一个计划,该计划旨在为一家船只租赁公司保留库存。该程序使用链表来保存有关库存的数据。除了按价格打印之外,我已经获得了所有功能。此功能用于将链表按照价格从低到高的顺序排序,然后打印列表。我认为我的排序算法没问题,但是我遇到了一个我找不到原因的段错误。任何帮助表示赞赏。以下代码是我按价格打印的功能。


  //creates a new list and copies every number from inventory over to this one
  //except add the values in order from lowest to highest by adding in order
  int i = 0;
  //initialize new list
  list_t *sorted = (list_t*)malloc(sizeof(list_t));
  sorted->size = list->size;
  sorted->head = NULL;
  sorted->tail = NULL;
  //make temp variable for iteration
  watercraft_t *init = list->head;
  watercraft_t *temp = list->head;
  watercraft_t *prev = NULL;
  for(i = 0; i < list->size; ++i){
    watercraft_t *new = (watercraft_t*)malloc(sizeof(watercraft_t));
    new  = init;
    if(sorted->head == NULL){
      new = sorted->head;
      new->next = NULL;
    }
    else if(new->total_price < temp->total_price){
      prev->next = new;
      new->next = temp;
    }
    else if(temp->next == NULL){
      temp->next = new;
      new->next = NULL;
    }
    prev = temp;
    temp = temp->next;
    init = init->next;
  }

这是保存数据的链表中的结构

typedef struct watercraft {
    char type[15];     // e.g. pontoon, sport boat, sailboat, fishing,
                       //      canoe, kayak, jetski, etc.
    char make[20];
    char model[30];
    int propulsion;    // 0 = none; 1 = outBoard; 2 = inBoard;
    char engine[15];   // Suzuki, Yamaha, etc.
    int hp;             // horse power
    char color[25];
    int length;        // feet
    double base_price;
    double total_price;
    accessories_t extras;
    struct watercraft *next;
} watercraft_t;

If there is any other code that is necessary for this problem please let me know. There are about 400 more lines of code for this project.

标签: csortinglinked-listsegmentation-fault

解决方案


推荐阅读