为了不剥削你的学习能力,我的这段代码没有注释。
请自行学习。
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define N 15 typedef struct Node { int value; int num; struct Node *next; }node,*pnode; int ss[N][2]; void range(pnode start) { int i,j,v_tp,n_tp; pnode tp; tp = start->next; for (i = 0;i < N-1;i++) { for (j = i;j < N;j++) { if (tp->next== NULL) continue; if ((tp->value) > (tp->next->value)) { v_tp = tp->value; tp->value = tp->next->value; tp->next->value = v_tp; n_tp = tp->num; tp->num = tp->next->num; tp->next->num = n_tp; } tp = tp->next; } tp = start->next; } tp = start->next; for (i = 0;i < N;i++) { ss[i][0] = tp->num; ss[i][1] = tp->value; tp = tp->next; } } int search( int x) { int m,n,k; m = 0; k=N; do { n = (m + k) / 2; if (ss[n][1] == x) return ss[n][0]; if (n == k || n == m) return -1; else if (ss[n][1] > x) k = n; else { m = n; } } while (k>=n&&n >= m); return -1; } void printf_link(pnode s) { int i = 0; pnode p; p = s->next; while (p!=NULL) { printf("%d,", p->value); p = p->next; } } void main() { pnode start,tmp,tmp2; int i,x; start = (pnode)malloc(sizeof(node)); tmp = start; printf("输入你的%d个数列:\n",N); for (i = 0;i < N;i++) { tmp2 = (pnode)malloc(sizeof(node)); scanf_s("%d", &tmp2->value); tmp2->num = i; tmp->next = tmp2; tmp = tmp2; } tmp->next= NULL; printf("您输入的数列为:"); printf_link(start); putchar(10); range(start); while(1) { printf("输入你要查询的值:"); if(scanf_s("%d", &x)==EOF) exit(1); i = search(x); if (i==-1) printf("无此数\n"); else printf("是第%d个值\n", i+1); } }
[此贴子已经被作者于2017-3-21 23:33编辑过]