【问题标题】:Sorting a linked list in ascending order in C在C中按升序对链表进行排序
【发布时间】:2015-05-03 06:31:08
【问题描述】:

我正在为我的 C 编程课程编写一个程序,该程序应该让我们有使用链表的经验。作业的最后一部分要求我们获取一个链表,并使用我们之前在程序中编写的 prepend 或 append 函数按升序对其进行排序。

struct lnode
{
  int datum;
  struct lnode *next;
};


struct lnode*
prepend(struct lnode *list, int x)
{
  struct lnode *node = (struct lnode *)malloc(sizeof(struct lnode));
  node -> datum = x;
  node -> next = list;
  list = node;
  return list;
}

struct lnode*
append(struct lnode *list, int x)
{
  if(list==NULL){
    list = (struct lnode *)malloc(sizeof(struct lnode));
    list -> datum = x;
    list -> next = NULL;
  }else{
    list -> next = append(list->next,x);li
  }
  return list;
}

上面是我们在课堂上设计的 append 和 prepend 函数。

下面是删除函数,我们在课堂上也做了:

struct lnode*
delete(struct lnode *list, int x)
{
  struct lnode* tmp;
  if(list == NULL){
    return list;
  }else if(list-> datum == x){
    tmp = list -> next;
    list -> next = NULL;
    free(list);
    list = tmp;
    return list;
  }else{
    list->next = delete(list->next,x);
    return list;
  }
}

int
find_smallest(struct lnode*list)
{
  int smallest;
  smallest = list->datum;
  while(list!=NULL){
    if(list->datum < smallest){
      smallest = list->datum;
    }
    list = list->next;
  }
  return smallest;
}

函数 find_smallest 将链表作为其输入,并应返回链表中的最小整数值。我已经多次测试了这个功能,它似乎工作得很好。

最后,下面的排序应该创建一个新的链表new_list,并应该追加列表中最小整数的值,然后从列表中删除该值,直到列表不再有任何值。

struct lnode*
sort(struct lnode *list)
{
  struct lnode *new_list;
  while(list != NULL && list->next != NULL){
    new_list = append(new_list, find_smallest(list));
    list = delete(list, find_smallest(list));
  }
  return new_list;
}

我遇到的问题是我似乎陷入了无限循环。 我运行了一个测试用例,在每次运行循环后打印 list 的元素,其中 list 最初是 5 4 1 2 3 并且一遍又一遍地打印出来的是 5 4 2 3 直到我强制程序停止。所以我相信它只能正确运行一次?

【问题讨论】:

  • 你也可以发布你的delete()函数吗?
  • 也许您应该在代码审查上发布或在 ideone 或任何其他在线编辑器上提供完整代码的链接,这样其他人可能很容易发现错误
  • @sasha codereview.stackexchange.com 仅适用于已经按预期工作的代码。这是题外话。另请阅读Be careful when recommending Code Review to askers
  • 始终建议不要强制转换 malloc 返回值。为什么不在这里?
  • @SimonAndréForsberg 哦。对于那个很抱歉。会记住这一点。谢谢。

标签: c sorting linked-list


【解决方案1】:

变量new_list 未在sort 函数中初始化。然后append 函数错误地附加到一个不存在的节点。

改变

struct lnode *new_list;

struct lnode *new_list = NULL;

sort 函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2015-12-08
    • 2012-08-02
    • 2012-10-07
    相关资源
    最近更新 更多