选择排序与链表的 [英] Selection sort with linked list's

查看:94
本文介绍了选择排序与链表的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下的数据结构:

so I have the following data structure:

struct scoreentry_node {
    struct scoreentry_node *next;
    int score;
    char name[1];    
}
;

typedef struct scoreentry_node *score_entry;

我基本上想创建inorderly消耗我的结构功能和基于名称升序排列。我想修改输入不分配任何内存或释放什么:

I basically want to create a function that consumes my structure inorderly and arrange them in ascending order based on the name. I want to modify the input without allocating any memory or freeing anything:

我试过你的建议

    void selectionsort(score_entry *a) {
    for (; *a != NULL; *a = (*a)->next) 
    {
      score_entry *minafteri = a;
      // find position of minimal element
      for (score_entry j = (*a)->next; j != NULL; j = j->next) {
      if (strcmp(j->name, (*minafteri)->name) == -1) {
         *minafteri = j;
      }
    }
     // swap minimal element to front
      score_entry tmp = *a;
      a = minafteri;
      *minafteri = tmp;
  }

}

和IM测试以下

score_entry x = add(8, "bob", (add( 8 , "jill", (add (2, "alfred", NULL)))));
iprint("",x);
selectionsort(&x);
iprint("", x);
clear(x);

,其中明确免费的整个列表。 iPrint的打印分数的和名称的在结构中。我的add函数是如下的

where clear free's the whole list. iprint prints the score's and name's in the struct. and my add function is as follow's

score_entry add(int in, char* n, score_entry en) {      
   score_entry r = malloc(sizeof(struct scoreentry_node) + strlen(n));
   r->score = in;
   strcpy(r->name, n);
   r->next = en;  
   return r;   
}

我得到堆错误,我的第二个打印不打印排序列表,它打印什么?有什么建议?

I'm getting heap errors and my second print doesn't print the sorted list, it prints nothing? any suggestions?.

推荐答案

除了按地址传递指针(见下文评论)你还需要解决你交换的元素太多

besides passing the pointer by address (see comments below) you also need to fix the way you swap elements too

void selectionsort(score_entry *a) {
  for (; *a != NULL; *a = (*a)->next) 
  {
     score_entry *minafteri = a;
     // find position of minimal element
     for (score_entry j = (*a)->next; j != NULL; j = j->next) {
       if (strcmp(j->name, (*minafteri)->name) == -1) {
         *minafteri = j;
       }
      }
     // swap minimal element to front
     score_entry tmp = *a;
     a = minafteri; // put the minimal node to current position
     tmp->next = (*a)->next ; //fix the links
     (*minafteri)->next=tmp; //fix the links
  }
}

这篇关于选择排序与链表的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆