我已经用这段代码对我的链表进行了排序。
由于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);
}
尝试将此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