所以我有一个链表,其中包含两个元素、一个读入的 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/