Advertisement
dmkozyrev

стэк

May 31st, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct node {
  5.     int value;
  6.     struct node *next;
  7. } Node;
  8.  
  9. int size(const Node *head);
  10. void print_stack(const Node* head);
  11. int top(const Node* head);
  12. int pop(Node **head);
  13. void push(Node **head, int value);
  14.  
  15. int main(){
  16.  
  17.     int i;
  18.     Node *head = NULL, *out;
  19.     for (i = 0; i < 10; i++) {
  20.         push(&head, i);
  21.     }
  22.     //out = head;
  23.  
  24.     print_stack(head);
  25.     //printf("size = %d\n", out -> value);
  26.     /*
  27.     while (head) {
  28.         printf("%d ", top(head));
  29.         printf("%d ", pop(&head));
  30.     }
  31.     */
  32.     return 0;
  33. }
  34.  
  35. void push(Node **head, int value){
  36.     Node *temp = malloc(sizeof(Node));
  37.     temp -> next = *head;
  38.     temp -> value = value;
  39.     *head = temp;
  40. }
  41.  
  42. int pop(Node **head){
  43.     Node *out;
  44.     int value;
  45.     if ( *head == NULL ) return 0;
  46.     out = *head;
  47.     *head = (*head) -> next;
  48.     value = out -> value;
  49.     free(out);
  50.     return value;
  51. }
  52.  
  53. int top(const Node* head) {
  54.     if ( head == NULL ) return 0;
  55.     return head->value;
  56. }
  57.  
  58. void print_stack(const Node* head) {
  59.     printf("stack > ");
  60.  
  61.     Node *n;
  62.     n = head;
  63.     while (n != NULL){
  64.         printf("%d ", n -> value);
  65.         n = n -> next;
  66.     }
  67.     printf("\n");
  68. }
  69.  
  70. int size(const Node *head) {
  71.     int size = 0;
  72.     while (head) {
  73.         size++;
  74.         head = head->next;
  75.     }
  76.     return size;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement