Advertisement
dmkozyrev

stack

May 31st, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 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. void main() {
  16.     /*
  17.     int i;
  18.     Node *head = NULL;
  19.     for (i = 0; i < 10; i++) {
  20.         push(&head, i);
  21.     }
  22.     printf("size = %d\n", size(head));
  23.     while (head) {
  24.         printf("%d ", top(head));
  25.         printf("%d ", pop(&head));
  26.     }
  27.     */
  28.     return 0;
  29. }
  30.  
  31. void push(Node **head, int value){
  32.     Node *temp = malloc(sizeof(Node));
  33.     temp -> next = *head;
  34.     temp -> value = value;
  35.     *head = temp;
  36. }
  37.  
  38. int pop(Node **head){
  39.     Node *out;
  40.     int value;
  41.     if ( *head == NULL ) return 0;
  42.     out = *head;
  43.     *head = (*head) -> next;
  44.     value = out -> value;
  45.     free(out);
  46.     return value;
  47. }
  48.  
  49. int top(const Node* head) {
  50.     if ( head == NULL ) return 0;
  51.     return head->value;
  52. }
  53.  
  54. void print_stack(const Node* head) {
  55.     printf("stack > ");
  56.     while (head) {
  57.         printf("%d ", head->value);
  58.         head = head->value;
  59.     }
  60.     printf("\n");
  61. }
  62.  
  63. int size(const Node *head) {
  64.     int size = 0;
  65.     while (head) {
  66.         size++;
  67.         head = head->next;
  68.     }
  69.     return size;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement