Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node
- {
- int val;
- struct node* next;
- }node_t;
- node_t* get_last(node_t *head)
- {
- node_t* cur=head;
- if (!cur)
- return NULL;
- while (cur->next)
- cur = cur->next;
- return cur;
- }
- int push(node_t ** head,int n)
- {
- node_t *last = get_last(*head);
- node_t *cur = malloc(sizeof(node_t));
- if (!cur)
- return EXIT_FAILURE;
- cur->val = n;
- cur->next = NULL;
- if (last == NULL)
- (*head)=cur;
- else
- last->next = cur;
- return EXIT_SUCCESS;
- }
- int pop(node_t ** head)
- {
- struct node *cur = (*head); //текущий узел
- struct node *prev = NULL; //предыдущий узел
- //Список пуст
- if (!(*head))
- return EXIT_FAILURE;
- while (cur->next)
- {
- prev = cur;
- cur = cur->next;
- }
- if (!prev)
- {
- free(*head);
- *head = NULL;
- } else
- {
- free(cur);
- prev->next = NULL;
- }
- return EXIT_SUCCESS;
- }
- int delete_all(node_t ** head)
- {
- node_t * prev = NULL;
- if (!(*head))
- return EXIT_FAILURE;
- while ((*head)->next)
- {
- prev = (*head);
- (*head) = (*head)->next;
- free(prev);
- prev = NULL;
- }
- free(*head);
- *head = NULL;
- return EXIT_SUCCESS;
- }
- void sort ( node_t ** head )
- {
- int sorted = 0;
- if (!(*head) || !((*head)->next))
- sorted = 1;
- while (!sorted)
- {
- node_t ** pv = head ;
- node_t * cur = *head ;
- node_t * nxt = (*head )->next ;
- sorted = 1;
- while ( nxt )
- {
- if ( cur ->val > nxt ->val )
- {
- cur ->next = nxt ->next ;
- nxt ->next = cur ;
- *pv = nxt;
- sorted = 0;
- }
- pv = &cur ->next ;
- cur = nxt ;
- nxt = nxt ->next ;
- }
- }
- }
- void output_list(struct node* head)
- {
- printf("\nStack : ");
- struct node * current = head;
- while (current != NULL)
- {
- printf("%d",current->val);
- current = current->next;
- }
- printf("\n");
- }
- int main()
- {
- // int am=5;
- node_t * head =NULL;
- push(&head,1);
- push(&head,3);
- push(&head,2);
- push(&head,4);
- // push(&head,2);
- // push(&head,0);
- sort (&head );
- output_list(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement