Advertisement
cd62131

Stack and Queue

Aug 4th, 2014
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define N 100
  4. struct stack {
  5.   int top;
  6.   int rear;
  7.   int element[N];
  8. };
  9. struct queue {
  10.   int top;
  11.   int rear;
  12.   int element[N];
  13. };
  14. void push(int x, struct stack *S) {
  15.   if (S->top == 0) {
  16.     printf("Error\n");
  17.     exit(1);
  18.   }
  19.   S->element[--S->top] = x;
  20. }
  21. void pop(struct stack *S) {
  22.   if (S->top >= N) {
  23.     printf("Error\n");
  24.     exit(1);
  25.   }
  26.   printf("%d ", S->element[S->top++]);
  27. }
  28. void enqueue(int x, struct queue *Q) {
  29.   if (Q->top == Q->rear) {
  30.     Q->rear = 0;
  31.     Q->top = 0;
  32.     Q->element[Q->rear++] = x;
  33.     return;
  34.   }
  35.   if (Q->rear == N) {
  36.     printf("Error\n");
  37.     exit(1);
  38.   }
  39.   Q->element[Q->rear++] = x;
  40. }
  41. void dequeue(struct queue *Q) {
  42.   if (Q->rear <= Q->top) {
  43.     printf("Error\n");
  44.     exit(1);
  45.   }
  46.   printf("%d ", Q->element[Q->top++]);
  47. }
  48. int main(void) {
  49.   int x;
  50.   struct stack S;
  51.   struct queue Q;
  52.   S.top = N;
  53.   Q.top = Q.rear = 0;
  54.   while (1) {
  55.     printf("整数を入力してください: ");
  56.     scanf("%d", &x);
  57.     if (x < 0) break;
  58.     push(x, &S);
  59.     enqueue(x, &Q);
  60.   }
  61.   printf("スタック構造の場合\n");
  62.   while (S.top < N)
  63.     pop(&S);
  64.   printf("\nキュー構造の場合\n");
  65.   while (Q.top < Q.rear)
  66.     dequeue(&Q);
  67.   printf("\n");
  68.   return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement