c - C语言中如何对链表进行排序?

标签 c sorting linked-list

所以我试图根据名称从小到大对链接列表进行排序。它对其进行排序,但它以相反或错误的方式对其进行排序。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

//declaring a struct
struct node {
    char *name;
    int num;
    struct node *next;  
};
struct node *list=NULL;

/*
 * insert()
 */

struct node *insert(char word2[], int val){
    struct node *tmp;

    tmp = malloc(sizeof(struct node));
    if(tmp ==NULL){
        fprintf(stderr, "out of memory\n");
        exit(1);
    }

    tmp->name = strdup(word2);
    tmp->num = val;
    tmp->next = list;
    list = tmp;

    return tmp;
}//read string

void print(){
    struct node *ptr;
    for(ptr= list; ptr!=NULL; ptr = ptr->next){
        printf(" %s/%d\n", ptr->name, ptr->num);
    }//for loop
}//print

void sort(){
    struct node *ptr1, *ptr2;
    char *tmp;

    for(ptr1 = list; ptr1!=NULL; ptr1 = ptr1->next){
        for(ptr2 = ptr1->next; ptr2!=NULL; ptr2 = ptr2->next){
            if(strcmp(ptr1->name, ptr2->name)>0){
                //ptr1->name is "greater than" ptr2->name - swap them
                tmp = ptr1->name;
                ptr1->name = ptr2->name;
                ptr1->name = tmp;
            }
        }
    }
}//sort

int main (){
    char buff[81];
    int status=0;
    int len;
    char word1[20];
    char word2[20];
    int val;
    //      char word3[20];

    while(fgets(buff, 81, stdin)>0){
        len = strlen(buff);

        if(buff[len-1]!='\n'){
            fprintf(stderr,"Error: string line length was too long\n");
            exit(1);
        }

        sscanf(buff, "%s %s %d", word1, word2, &val);

        if(strcmp(word1, "insert")==0){
            insert(word2, val);
            sort();
        }else if(strcmp(word1, "print")==0){
            print();
        }else{

        }

    }//while loop

    return status;
}

这就是我运行时输入的样子。

"insert a 1"
"insert b 2"
"insert c 3"
"print"

输出

c/3
b/2
a/1

如果尝试更改我的排序方法条件,但它始终以错误的方式排序。我似乎找不到这个错误。任何帮助将不胜感激。但我的输出应该是这样的

期望的输出

a/1
b/2
c/3

最佳答案

如果在每次插入后进行排序,则不需要完整的冒泡排序,只需一轮。

void sort()
{
  struct node *ptr1 = list;
  char *tmpname;
  int tmpnum;

  while (ptr1->next != NULL) { 
    if (strcmp(ptr1->name, ptr1->next->name) > 0) {
      // swap content in this case, not the nodes
      tmpname = ptr1->name;
      tmpnum = ptr1->num;

      ptr1->name = ptr1->next->name;
      ptr1->num = ptr1->next->num;

      ptr1->next->name = tmpname;
      ptr1->next->num = tmpnum;

    }
    ptr1 = ptr1->next;
  }
}

关于c - C语言中如何对链表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886258/

相关文章:

c - 在调用 execl() 之后退出 (0) 是否有意义?

c++ - 使用数组对 C++ 中的链表进行排序以对其数据进行排序

Java - 当文件中的数据超出限制时打印消息?

javascript - Microsoft Edge array.sort(compareFunction) 排序不正确

django - 非常困惑...在 Django 中使用 'annotate' 的问题

c - 删除链表中包含用户输入的字母的元素

java - 删除链表中具有给定键的节点

c - 轮询立即从司机那里退出

c 程序未按预期输出

c - 从不兼容指针类型/解引用指针到不完整类型的赋值