fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct list {
  5. struct list *m_pNext;
  6. int m_value;
  7. } List;
  8.  
  9. List *list_insert(List *pHead, int value)
  10. {
  11. List *pNew = malloc(sizeof(List));
  12. pNew->m_value = value;
  13. pNew->m_pNext = pHead;
  14.  
  15. return pNew;
  16. }
  17.  
  18. List *list_sorted_insert(List *pHead, int value)
  19. {
  20. List *p, *pPrev = NULL;
  21.  
  22. for (p = pHead; p; p = p->m_pNext) {
  23. if (value <= p->m_value) {
  24. break;
  25. }
  26. pPrev = p;
  27. }
  28.  
  29. List *pNew = list_insert(p, value);
  30.  
  31. if (pPrev) {
  32. pPrev->m_pNext = pNew;
  33. } else {
  34. pHead = pNew;
  35. }
  36.  
  37. return pHead;
  38. }
  39.  
  40. void list_print(List *pHead)
  41. {
  42. List *p;
  43.  
  44. for (p = pHead; p; p = p->m_pNext) {
  45. printf("%d ", p->m_value);
  46. }
  47. printf("\n");
  48. }
  49.  
  50. void list_free(List *pHead)
  51. {
  52. List *p, *q;
  53.  
  54. for (p = pHead; p; p = q) {
  55. q = p->m_pNext;
  56. free(p);
  57. }
  58. }
  59.  
  60. int main()
  61. {
  62. List *pHead = NULL;
  63. int value;
  64.  
  65. for (; ;) {
  66. if (scanf("%d", &value) < 1) {
  67. continue;
  68. }
  69. if (value < 0) {
  70. break;
  71. }
  72.  
  73. pHead = list_sorted_insert(pHead, value);
  74. }
  75.  
  76. list_print(pHead);
  77.  
  78. list_free(pHead);
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0.01s 1812KB
stdin
8 8 0 1 6 8 0 0 -1
stdout
0 0 0 1 6 8 8 8