函数cmp为什么注释部分换掉1,2不起作用?
#include
#include
typedef struct node* list;
struct node {
int data;
list next;
};
int cmp(const void* a,const void* b) {
list p = *(list*)a;
list *q = (list)b;//1
return p->data - (*q)->data;//2
/*list q = *(list*)a;
return p->data - q->data;*/
}
list sort(list L) {
int i, n = length(L);
list p = L;
list(*a) = (list)malloc(n * sizeof(struct node));
i = 0;
while (p = p->next) {
a[i] = p;
i++;
}
qsort(a, n, sizeof(list), cmp);
p = L;
for (int i = 0; i < n; i++) {
p->next = a[i];
p = p->next;
}
p->next = NULL;
return L;
}
//完整代码
#include
#include
typedef struct node* list;
struct node {
int data;
list next;
};
list creat() {
list p;
p = (list)malloc(sizeof(struct node));
p->next = NULL;
return p;
}
list insert(list L, int data) {
list p;
p = (list)malloc(sizeof(struct node));
p->data = data;
p->next = L->next;
L->next = p;
return L;
}
int length(list L) {
list p = L;
int count = 0;
while (p = p->next) count++;
return count;
}
int cmp(const void* a,const void* b) {
list p = *(list*)a;
list *q = (list)b;
return p->data - (*q)->data;
/*list q = *(list*)a;
return p->data - q->data;*/
}
list sort(list L) {
int i, n = length(L);
list p = L;
list(*a) = (list)malloc(n * sizeof(struct node));
i = 0;
while (p = p->next) {
a[i] = p;
i++;
}
qsort(a, n, sizeof(list), cmp);
p = L;
for (int i = 0; i < n; i++) {
p->next = a[i];
p = p->next;
}
p->next = NULL;
return L;
}
void print(list L) {
list p = L;
while (p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
int main() {
list L = creat();
int n;
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
insert(L, rand() % n);
}
//print(L);
L = sort(L);
//print(L);
return 0;
}
list *q = (list*)b;