c - C 中链表的降序排序函数?

标签 c sorting linked-list

所以我有一个链表,其中包含两个元素、一个读入的 3 个字符的字符串和一个整数值。我需要按字符串各自的 int 值按降序对字符串进行排序。我将链接整个代码块,然后准确指出我遇到困难的地方。

代码运行良好,直到遇到 sort() 函数。然后它陷入了无限循环。当用户输入字符串“end”时,程序应该结束。

void sort() {
    struct node *ptr1, *ptr2;
    ptr1 = ptr2 = head;
    while(ptr1 != NULL){
        ptr2 = ptr1;
        while(ptr2 != NULL) {
            if(ptr1->val < ptr2->val){
                ptr2 = ptr2->next;
            }
        }
    }
}


int main(void) {
    char str[CMDSIZE];
    head = NULL;
    struct node *temp;
    int randomnumber;
    randomnumber = (rand() % 10) + 1;


    while(strcmp(str, "end") != 0) {
        printf("Enter your command: ");
        fflush(stdout);
        scanf("%[^\n]%*c", str);
        insert(str, randomnumber);
        randomnumber = (rand() % 10) + 1;
    }
    sort();
    print();

}

完整代码如下:

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

#define CMDSIZE 4

struct node
{
    char cmd[4];
    int val;
    struct node *next;
};

struct node *head = NULL;
struct node *curr = NULL;


void insert(char command[], int x) {
    struct node *temp;
    temp = (struct node*)malloc(sizeof(struct node));
    strcpy(temp->cmd, command);
    temp->val = x;
    temp->next = head;
    head = temp;
}

void print() {
    struct node *temp;
    temp = head;
    printf("\n Linked List Contents : \n");
    while(temp!=NULL){
        printf(" Node contains :\n %s %d \n", temp->cmd, temp->val);
        temp=temp->next;
    }
}

void sort() {
    struct node *ptr1, *ptr2;
    ptr1 = ptr2 = head;
    while(ptr1 != NULL){
        ptr2 = ptr1;
        while(ptr2 != NULL) {
            if(ptr1->val < ptr2->val){
                ptr2 = ptr2->next;
            }
        }
    }
}


int main(void) {
    char str[CMDSIZE];
    head = NULL;
    struct node *temp;
    int randomnumber;
    randomnumber = (rand() % 10) + 1;


    while(strcmp(str, "end") != 0) {
        printf("Enter your command: ");
        fflush(stdout);
        scanf("%[^\n]%*c", str);
        insert(str, randomnumber);
        randomnumber = (rand() % 10) + 1;

    }
    sort();
    print();

}

我使用随机 3 个字符串作为输入,直到输入“end”并且排序函数运行。

使用 sort() 输出:

Enter your command: lll
Enter your command: ooo
Enter your command: man
Enter your command: bmi
Enter your command: end

不带 sort() 的输出:

 Linked List Contents : 
 Node contains :
 end 9 
 Node contains :
 two 4 
 Node contains :
 one 10 
 Node contains :
 lll 8 

最佳答案

在这个循环中

while(ptr2 != NULL) {
   if(ptr1->val < ptr2->val){
       ptr2 = ptr2->next;
   }
}

如果 ptr2->val >= ptr1->val ptr2 在循环的下一次迭代中不会更改,这意味着循环永远不会终止。

关于c - C 中链表的降序排序函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42958582/

相关文章:

c - 打印出链表的输入 [C]

c - C 中链表的问题

c - 尝试打印链接列表中的节点时,该节点似乎为空

c - memcpy [或不?] 和多线程 [std::thread from c++11]

c - 错误: expected constructor,析构函数,或 '('之前的类型转换

c - "sorted"的确切含义

c - 为什么我在大输入时遇到 scanf 的段错误

c# - 将 C++ 指针结构转换为 C#

c - 动态数组代码不断崩溃

algorithm - 排序需要多少操作?