Chinaunix首页 | 论坛 | 博客
  • 博客访问: 512583
  • 博文数量: 398
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 14
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-21 16:02
个人简介

嵌入式屌丝

文章分类

全部博文(398)

文章存档

2013年(398)

我的朋友

分类: LINUX

2013-08-21 17:16:43

原文地址:用数组实现栈和队列C++ 作者:cherish568


点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <stdio.h>

  3. class Stack
  4. {
  5. private:
  6.    int ele[100];
  7.    int top;
  8. public:
  9.    Stack() {
  10.       top = 0;
  11.    }
  12.    void push(int v) {
  13.       ele[top++] = v;
  14.    }
  15.    int pop() {
  16.       if(isEmpty()) {
  17.          printf("The stack is Empty.\n");
  18.          return -1;
  19.       }
  20.       return ele[--top];
  21.    }
  22.    bool isEmpty() {
  23.       return top == 0;
  24.    }
  25.    ~Stack() {
  26.    }
  27. };

  28. #define SIZE 100
  29. class Queue
  30. {
  31. private:
  32.    int ele[SIZE];
  33.    int head;
  34.    int tail;
  35. public:
  36.    Queue() {
  37.       head = 0;
  38.       tail = 0;
  39.    }
  40.    bool isFull() {
  41.       return (tail+1) % SIZE == head;
  42.    }
  43.    bool isEmpty() {
  44.       return head == tail;
  45.    }
  46.    void enqueue(int val) {
  47.       if(isFull()) {
  48.          printf("The queue is full, can not enqueue for: %d\n", val);
  49.          return;
  50.       }
  51.       ele[tail] = val;
  52.       tail = (tail+1) %SIZE;
  53.    }
  54.    int dequeue() {
  55.       if(isEmpty()) {
  56.          printf("The queue is empty, can not dequeue.\n");
  57.          return -1;
  58.       }
  59.       int value = ele[head];
  60.       head = (head+1)%SIZE;
  61.       return value;
  62.    }
  63. };

  64. int main()
  65. {
  66.    Stack s;
  67.    s.push(123);
  68.    s.push(12);
  69.    while(!s.isEmpty()) {
  70.       printf("%d ", s.pop());
  71.    }
  72.    printf("\n");

  73.    Queue q;
  74.    q.enqueue(88);
  75.    q.enqueue(13);
  76.    q.enqueue(123);
  77.    while(!q.isEmpty()) printf("%d ", q.dequeue());
  78.    printf("\n");
  79.    system("pause");
  80. }
[root@localhost C++]# g++ push.cpp -o push
[root@localhost C++]# ./push
12 123
88 13 123
sh: pause: command not found
阅读(681) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~