能否指点一下思路,无从下手啊……万分感谢
编写一个程序,实现对任意输入的整数进行排序。其中整数的个数n不是一个确定的数值。不能使用数组int array[n]表示,要求通过用户在程序运行中输入n的值,并采用动态分配内存的方式来为数组分配空间。重点就是使用动态分配内存,这个使用得不熟练。
2015-03-29 13:10
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define SwapInt(a, b) (a) ^= (b), (b) ^= (a), (a) ^= (b)
typedef struct node {
int data;
struct node *next;
} ND, *PN;
void free_list(PN head) {
PN cur = NULL;
while(head) {
cur = head->next;
free(head);
head = cur;
}
}
int main(void) {
PN head, p, cur;
head = p = cur = NULL;
puts("输入数组元素 空格分隔 非法赋值则结束输入");
while((p = malloc(sizeof(ND))) != NULL) {
if((scanf("%d", &(p->data))) != 1) {
free(p);
break;
}
p->next = head;
head = p;
}
for(p = head; p; p = p->next) {
for(cur = p->next; cur; cur = cur->next) {
if(p->data > cur->data)
SwapInt(p->data, cur->data);
}
}
puts("升序排列后输出:");
for(p = head; p; p = p->next) {
printf("%d ", p->data);
}
free_list(head);
return 0;
}

2015-03-29 14:14
程序代码:#include <stdio.h>
#include <stdlib.h>
#define MALLOC(p, size, type)\
if(!(p = (type)malloc(size))) {\
fprintf(stderr, "malloc error...");\
exit(EXIT_FAILURE);\
}
#define FREE(p)\
if(p){\
free(p);\
p = NULL;\
}
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
#define COMPARE(x, y) (((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1)
void sort(int list[], int n); //选择排序整数数组
int main(int argc, char **argv) {
int i, n, *num;
puts("输入数组长度: ");
while((scanf("%d", &n)) != 1 || n < 1) while(getchar() != '\n');
MALLOC(num, n * sizeof(int), int*);
puts("输入数组元素: ");
for(i = 0; i < n; i++)
while((scanf("%d", num + i)) != 1) while(getchar() != '\n');
sort(num, n);
puts("\n排序后的数组:");
for(i = 0; i < n; i++)
printf("%d\t", num[i]);
puts("");
FREE(num);
return 0;
}
void sort(int list[], int n) {
int i, j, min, temp;
for(i = 0; i < n - 1; i++) {
min = i;
for(j = i + 1; j < n; j++) {
if(list[j] < list[min])
min = j;
}
SWAP(list[i], list[min], temp);
}
}

2015-03-29 16:58
2015-03-29 18:58

2015-03-29 19:02
2015-03-29 19:12
2015-03-29 20:24
2015-03-29 21:50
2015-03-29 22:10
2015-03-29 22:15