Advertisement
Tobiahao

Kolokwium_Stos

Apr 26th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. // Implementacja Stosu
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct stack_node{
  6.     int data;
  7.     struct stack_node *next;
  8. } *top = NULL;
  9.  
  10. struct stack_node *push(struct stack_node *top, int data)
  11. {
  12.     struct stack_node *new_node = (struct stack_node*)malloc(sizeof(struct stack_node));
  13.     if(new_node){
  14.         new_node->data = data;
  15.         new_node->next = top;
  16.         top = new_node;
  17.     }
  18.     return top;
  19. }
  20.  
  21. int pop(struct stack_node **top)
  22. {
  23.     int tmp_data = -1;
  24.     if(top){
  25.         tmp_data = (*top)->data;
  26.         struct stack_node *tmp = (*top)->next;
  27.         free(*top);
  28.         *top = tmp;
  29.     }
  30.     return tmp_data;
  31. }
  32.  
  33. int peek(struct stack_node *top)
  34. {
  35.     if(top)
  36.         return top->data;
  37.     else{
  38.         fprintf(stderr, "Stos jest pusty\n");
  39.         return -1;
  40.     }
  41. }
  42.  
  43. int main(void)
  44. {
  45.     top = push(top, 2);
  46.     top = push(top, 4);
  47.     top = push(top, 6);
  48.     printf("Szczytowy element stosu: %d\n", peek(top));
  49.     printf("Usunieto element: %d\n", pop(&top));
  50.     printf("Szczytowy element stosu: %d\n", peek(top));
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement