我已使用此代码对链接列表进行了排序。
由于data2
,它从最小到最大排序。
例如:我列表的输出是:
1. data1: 3 data2: 4
2. data1: 7 data2: 3
3. data1: 5 data2: 0
4. data1:-6 data2: 2
5. data1: 4 data2: 1
并做到了这一点:
1. data1: 5 data2: 0
2. data1: 4 data2: 1
3. data1:-6 data2: 2
4. data1: 7 data2: 3
5. data1: 3 data2: 4
它工作正常,但我希望它从最大到最小排序。
如果将此行if (iterbub->us > iterbub->next->us)
更改为
if (iterbub->us < iterbub->next->us)
,但它的工作方式如下:
1. data1: 3435431 data2: 7343443
2. data1: 3 data2: 4
3. data1: 7 data2: 3
4. data1:-6 data2: 2
5. data1: 4 data2: 1
似乎有一个小问题,我该如何解决? (首先看起来不太好)
typedef struct node{
int katsayi;
int us;
struct node *next;
} Polinomlar;
void degistir(Polinomlar *a, Polinomlar *b) {
int temp = a->us;
a->us = b->us;
b->us = temp;
int temp2 = a->katsayi;
a->katsayi = b->katsayi;
b->katsayi = temp2;
}
void sirala(Polinomlar *p3)
{
int degisim, i;
node *iterbub;
if (p3 == NULL)
return;
do
{
degisim = 0;
iterbub = p3;
while (iterbub->next != NULL)
{
if (iterbub->us > iterbub->next->us)
{
degistir(iterbub, iterbub->next);
degisim = 1;
}
iterbub = iterbub->next;
}
} while (degisim);
}
答案 0 :(得分:0)
尝试按降序将if (iterbub->us > iterbub->next->us)
更改为if (iterbub->us < iterbub->next->us)
。
#include<stdlib.h>
#include<stdio.h>
typedef struct node{
int katsayi;
int us;
struct node *next;
} Polinomlar;
void degistir(Polinomlar *a, Polinomlar *b) {
int temp = a->us;
a->us = b->us;
b->us = temp;
int temp2 = a->katsayi;
a->katsayi = b->katsayi;
b->katsayi = temp2;
}
void sirala(Polinomlar *p3)
{
int degisim, i;
Polinomlar *iterbub;
if (p3 == NULL)
return;
do
{
degisim = 0;
iterbub = p3;
while (iterbub->next != NULL)
{
if (iterbub->us < iterbub->next->us)
{
degistir(iterbub, iterbub->next);
degisim = 1;
}
iterbub = iterbub->next;
}
}while (degisim);
}
int main()
{
Polinomlar* x = (Polinomlar*)malloc(sizeof(Polinomlar));
x->katsayi = 5;
x->us = 10;
x->next = (Polinomlar*)malloc(sizeof(Polinomlar));
x->next->katsayi = 5;
x->next->us = 20;
x->next->next = (Polinomlar*)malloc(sizeof(Polinomlar));
x->next->next->katsayi = 15;
x->next->next->us = 30;
x->next->next->next = NULL;
sirala(x);
Polinomlar* x1 = x;
while(x1!=NULL)
{
printf("%d " , x1->us);
x1 = x1->next;
}
}
输出:30 20 10