Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6. int val;
  7. struct node* next;
  8.  
  9. }node_t;
  10.  
  11. node_t* get_last(node_t *head)
  12. {
  13. node_t* cur=head;
  14. if (!cur)
  15. return NULL;
  16. while (cur->next)
  17. cur = cur->next;
  18. return cur;
  19. }
  20. int push(node_t ** head,int n)
  21. {
  22. node_t *last = get_last(*head);
  23. node_t *cur = malloc(sizeof(node_t));
  24. if (!cur)
  25. return EXIT_FAILURE;
  26. cur->val = n;
  27. cur->next = NULL;
  28. if (last == NULL)
  29. (*head)=cur;
  30. else
  31. last->next = cur;
  32.  
  33. return EXIT_SUCCESS;
  34. }
  35. int pop(node_t ** head)
  36. {
  37. struct node *cur = (*head); //текущий узел
  38. struct node *prev = NULL; //предыдущий узел
  39.  
  40. //Список пуст
  41. if (!(*head))
  42. return EXIT_FAILURE;
  43.  
  44. while (cur->next)
  45. {
  46. prev = cur;
  47. cur = cur->next;
  48. }
  49.  
  50. if (!prev)
  51. {
  52. free(*head);
  53. *head = NULL;
  54. } else
  55. {
  56. free(cur);
  57. prev->next = NULL;
  58. }
  59. return EXIT_SUCCESS;
  60. }
  61. int delete_all(node_t ** head)
  62. {
  63. node_t * prev = NULL;
  64.  
  65. if (!(*head))
  66. return EXIT_FAILURE;
  67.  
  68. while ((*head)->next)
  69. {
  70. prev = (*head);
  71. (*head) = (*head)->next;
  72. free(prev);
  73. prev = NULL;
  74. }
  75. free(*head);
  76. *head = NULL;
  77.  
  78. return EXIT_SUCCESS;
  79. }
  80. void sort ( node_t ** head )
  81. {
  82. int sorted = 0;
  83.  
  84. if (!(*head) || !((*head)->next))
  85. sorted = 1;
  86.  
  87. while (!sorted)
  88. {
  89. node_t ** pv = head ;
  90. node_t * cur = *head ;
  91. node_t * nxt = (*head )->next ;
  92.  
  93. sorted = 1;
  94.  
  95. while ( nxt )
  96. {
  97. if ( cur ->val > nxt ->val )
  98. {
  99. cur ->next = nxt ->next ;
  100. nxt ->next = cur ;
  101. *pv = nxt;
  102.  
  103. sorted = 0;
  104. }
  105. pv = &cur ->next ;
  106. cur = nxt ;
  107. nxt = nxt ->next ;
  108. }
  109. }
  110. }
  111. void output_list(struct node* head)
  112. {
  113. printf("\nStack : ");
  114. struct node * current = head;
  115. while (current != NULL)
  116. {
  117. printf("%d",current->val);
  118. current = current->next;
  119. }
  120. printf("\n");
  121. }
  122.  
  123. int main()
  124. {
  125. // int am=5;
  126. node_t * head =NULL;
  127.  
  128. push(&head,1);
  129. push(&head,3);
  130. push(&head,2);
  131. push(&head,4);
  132. // push(&head,2);
  133. // push(&head,0);
  134.  
  135. sort (&head );
  136. output_list(head);
  137. return 0;
  138. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement