题目: 从键盘输入若干个正整数, 按从小到大的顺序输出. 输入负数表示输入结束. 用链表实现….

  • Post author:
  • Post category:其他


ContractedBlock.gif
ExpandedBlockStart.gif

Code




//


题目: 从键盘输入若干个正整数, 按从小到大的顺序输出. 输入负数表示输入结束. 用链表实现.





#include


<


stdio.h


>



#include


<


stdlib.h


>





#define


null 0



struct


Node

{




int


value;



struct


Node


*


next;

};



int


main(


int


argc,


char


*


argv[])

{


Node


*


p,


*


q,


*


r;



int


temp;

Node


*


h;



/*


定义头节点


*/



h


=


(


struct


Node


*


)malloc(


sizeof


(


struct


Node));

h


->


value


=







1


;

h


->


next


=




null


;



while


(


1


)

{


scanf(





%d





,


&


temp);



if


(temp


<




0


)



break


;



/*


为新输入的数据定义节点


*/



p


=


(


struct


Node


*


)malloc(


sizeof


(


struct


Node));

p


->


value


=


temp;



/*


寻找插入位置


*/



q


=


h;

r


=


h;



while


(q


!=




null




&&


q


->


value


<


p


->


value)

{


r


=


q;

q


=


q


->


next;

}



/*


插入


*/



r


->


next


=


p;

p


->


next


=


q;

}



/*


输出链表中的数据, 并释放申请的节点空间


*/



q


=


h


->


next;

free(h);



while


(q)

{


printf(





%5d





, q


->


value);

r


=


q;

q


=


q


->


next;

free(r);

}



return




0


;

}


转载于:https://www.cnblogs.com/froster/archive/2009/05/17/1458837.html