0

我曾尝试为我的链表程序构建一个排序算法,该算法将通过检查第一个元素与第二个、第三个等,然后将第二个元素与其余元素等进行比较,将我的链表按字母顺序排序但它不是工作。怎么了?

   struct list* sort_list(struct list *head)
    {
    struct list *current= (struct list*)malloc(sizeof(struct list));
    struct list *previous=(struct list*)malloc(sizeof(struct list));
    struct list *point=(struct list*)malloc(sizeof(struct list));

    char tmp[30];

      current = head;
      previous = NULL;
      point=head;

        while(point!=NULL)
        {
           while (current != NULL) 
           {
               if(strcmp(point->data,current->data)>0)
               {
                  swap(head,point,current);
               }

               previous = current;

               current = current->next;
            }

          point=point->next;
      }

      return head;

}




    void swap(struct list *head,struct list *first,struct list *second) {

    char *tempValue;
    tempValue = first->data;
    first->data = second->data;
    second->data = tempValue;
}

列表结构:

struct list
{
char *data;
struct list *next;
}list;
4

2 回答 2

0

代替

while (point != NULL) {
    while (current != NULL) {

经过

while (point != NULL) {
    current = point->next;
    while (current != NULL) {
于 2013-08-29T14:43:43.123 回答
-1

将所有列出的代码替换为:

std::list<char> myList;

// fill my list with a bunch of characters

myList.sort();

或内存效率稍高的版本:

std::string myList;

// fill my list with a bunch of characters

std::sort(myList.begin(), myList.end());
于 2013-08-29T14:50:43.033 回答