Advertisement
cd62131

Stack and Queue

Jul 1st, 2014
1,216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct list_t list_t;
  4. struct list_t {
  5.   int data;
  6.   list_t *link;
  7. };
  8. list_t *new_list(int data) {
  9.   list_t *new = (list_t *) malloc(sizeof(list_t));
  10.   new->data = data;
  11.   new->link = NULL;
  12.   return new;
  13. }
  14. list_t *top = NULL;
  15. void push(int data) {
  16.   list_t *new = new_list(data);
  17.   if (!top) {
  18.     top = new;
  19.     return;
  20.   }
  21.   new->link = top;
  22.   top = new;
  23. }
  24. int pop(void) {
  25.   int data;
  26.   if (!top) {
  27.     fprintf(stderr, "can't pop\n");
  28.     return -1;
  29.   }
  30.   data = top->data;
  31.   top = top->link;
  32.   return data;
  33. }
  34. list_t *head = NULL, *tail = NULL;
  35. void enqueue(int data) {
  36.   list_t *new = new_list(data);
  37.   if (!head) head = new;
  38.   if (!tail) tail = new;
  39.   head->link = new;
  40.   head = new;
  41. }
  42. int dequeue(void) {
  43.   int data;
  44.   if (!tail) {
  45.     fprintf(stderr, "can't dequeue\n");
  46.     return -1;
  47.   }
  48.   data = tail->data;
  49.   tail = tail->link;
  50.   return data;
  51. }
  52. int main(void) {
  53.   int i;
  54.   for (i = 0; i < 5; i++) push(i);
  55.   for (i = 0; i < 6; i++) printf("%d, ", pop());
  56.   puts("");
  57.   for (i = 0; i < 5; i++) enqueue(i);
  58.   for (i = 0; i < 6; i++) printf("%d, ", dequeue());
  59.   puts("");
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement