2015-03-02 48 views
3

我对我的C语言编程过程中的程序是应该给我们使用链表工作经验。作业的最后部分之一要求我们采用链接列表,并使用我们之前在程序中编写的prepend或append函数以升序排序。以升序排列链表用C

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; 
} 

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

+2

你可以发布你的'delete()'函数吗? – wimh 2015-03-02 19:18:34

+0

也许你应该张贴在代码审查或提供有关ideone或任何其他在线编辑器完成代码的链接可能是容易让别人误以为找到这样 – sashas 2015-03-02 21:00:42

+1

@sasha codereview.stackexchange.com仅供如预期已经是运行的代码。这是那里的话题。另请阅读[向代理推荐Code Review时要小心](http://meta.stackoverflow.com/questions/253975/be-careful-when-recommending-code-review-to-askers) – 2015-03-02 21:40:06

回答

1

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

变化

struct lnode *new_list; 

struct lnode *new_list = NULL; 

sort功能。