Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4.  
  5. typedef struct node_s
  6. {
  7. int data;
  8. struct node_s *next, *prev; // previous
  9. } node_s;
  10.  
  11. node_s *init(int a);
  12. void print_list(node_s *lst);
  13. void add(node_s *lst, int a);
  14. void destruct(node_s *lst);
  15.  
  16. void sort_list(node_s *lst)
  17. {
  18. node_s *p1 = lst, *p2 = lst, *p3;
  19. int temp;
  20.  
  21. do
  22. {
  23. p2 = lst;
  24. do
  25. {
  26. p3 = p2->next;
  27. if (p2->data > p3->data)
  28. {
  29. temp = p2->data;
  30. p2->data = p3->data;
  31. p3->data = temp;
  32. }
  33.  
  34. p2 = p2->next;
  35. } while (p2 != lst);
  36. p1 = p1->next;
  37. printf("\n");
  38. } while (p1 != lst);
  39. }
  40.  
  41. int main(void)
  42. {
  43. int data;
  44. node_s *temp;
  45.  
  46. printf("Введите элементы:");
  47. scanf("%d", &data);
  48.  
  49. node_s *lst = init(data);
  50.  
  51. for (int i = 0; i < 5; i++)
  52. {
  53. scanf("%d", &data);
  54. add(lst, data);
  55. }
  56.  
  57. printf("ДО:\n");
  58. print_list(lst);
  59. puts("\n\n");
  60.  
  61. sort_list(lst);
  62.  
  63. puts("\n\n");
  64. printf("Отсортирован:\n");
  65. print_list(lst);
  66.  
  67. destruct(lst);
  68.  
  69. return 0;
  70. }
  71.  
  72. void add(node_s *lst, int a)
  73. {
  74. node_s *temp = malloc(sizeof(node_s));
  75. temp->data = a;
  76. temp->next = lst->next;
  77. temp->prev = lst;
  78.  
  79. node_s *lst_next = lst->next;
  80. lst->next = temp;
  81. if (lst_next)
  82. lst_next->prev = temp;
  83.  
  84. // temp->ptr = lst->ptr;
  85. // lst->ptr = temp;
  86. }
  87.  
  88. node_s *init(int a)
  89. {
  90. node_s *lst = (node_s *)malloc(sizeof(node_s));
  91. lst->data = a;
  92. lst->next = lst;
  93. lst->prev = lst;
  94. return lst;
  95. }
  96.  
  97. void print_list(node_s *lst)
  98. {
  99. node_s *p = lst;
  100. if (!lst)
  101. return;
  102. do
  103. {
  104. printf("%d ", p->data);
  105. p = p->next;
  106. } while (p != lst);
  107. }
  108.  
  109. void destruct(node_s *lst)
  110. {
  111. node_s *temp = lst;
  112. node_s *p = lst;
  113.  
  114. if (!lst)
  115. return;
  116. do
  117. {
  118. temp = temp->next;
  119. free(p);
  120. p = temp;
  121. } while (p != lst);
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement