fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5. int val;
  6. struct node *next;
  7. } Node;
  8.  
  9. Node *head = NULL;
  10.  
  11. Node* createN(int x) {
  12. Node *newnode = (Node *)malloc(sizeof(Node));
  13. newnode->val = x;
  14. newnode->next = NULL;
  15. return newnode;
  16. }
  17.  
  18. void freeL() {
  19. Node *p;
  20. while (head != NULL) {
  21. p = head->next;
  22. free(head);
  23. head = p;
  24. }
  25. }
  26.  
  27. void printL() {
  28. Node *p = head;
  29. while (p != NULL) {
  30. printf("%d ", p->val);
  31. p = p->next;
  32. }
  33. printf("\n");
  34. }
  35.  
  36. void makeL(int n, int a[]) {
  37. head = NULL; // リストを初期化
  38.  
  39. for (int i = 0; i < n; i++) {
  40. Node *new_node = createN(a[i]); // 新しいノードを作成
  41. if (head == NULL || head->val >= new_node->val) {
  42. // 先頭に挿入
  43. new_node->next = head;
  44. head = new_node;
  45. } else {
  46. // 適切な位置を探して挿入
  47. Node *p = head;
  48. while (p->next != NULL && p->next->val < new_node->val) {
  49. p = p->next;
  50. }
  51. new_node->next = p->next;
  52. p->next = new_node;
  53. }
  54. }
  55. }
  56.  
  57. int main(void) {
  58. int i, n;
  59. int *a;
  60. scanf("%d", &n);
  61. a = (int *)malloc(sizeof(int) * n);
  62. for (i = 0; i < n; i++) {
  63. scanf("%d", &a[i]);
  64. }
  65. makeL(n, a);
  66. printL();
  67. freeL();
  68. free(a);
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0s 5280KB
stdin
8
21 55 5 13 8 2 34 3
stdout
2 3 5 8 13 21 34 55