查找最小的 k 个元素
题目:输入 n 个整数,输出其中最小的 k 个。
题目:输入 n 个整数,输出其中最小的 k 个。
例如输入 1,2,3,4,5,6,7 和 8 这 8 个数字,则最小的 4 个数字为 1,2,3 和 4。
#include <stdio.h>
#include <stdlib.h>
typedef struct Linklist{
int data;
struct Linklist *next;
}Linklist;
void insertValue(Linklist * &head,int value){
Linklist *listnode = (Linklist *)malloc(sizeof(Linklist));
printf("listnode addr:%d\n",listnode);
listnode->data = value;
Linklist *m,*pre;
if(head==NULL){
head = listnode;
printf("head addr:%d\n",head->data);
head->next = NULL;
printf("test\n");
return;
}
m = head;
while(m!=NULL){
if(m->data>value){
if(m==head){
listnode->next = head;
head = listnode;
return;
}
break;
}
pre = m;
m = m->next;
}
pre->next = listnode;
listnode->next = m;
}
main(){
int n,k,i;
Linklist *head,*p;
head = NULL;
printf("input the n and k:\n");
scanf("%d %d",&n,&k);
if(k>n) exit(-1);
int *a = (int *)malloc(sizeof(int));
printf("input the array:\n");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
printf("%d\n",a[i]);
insertValue(head,a[i]);
}
p = head;
printf("the minimum %d elements are:\n",k);
for(i=0;i<k;i++){
printf("%d\t",p->data);
p = p->next;
}
system("pause");
}