基本的操作需要:入栈,出栈,返回栈顶元素,是否为空栈。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class MyStack
 5 {
 6 private:
 7     char* stack;     // 栈空间的指针
 8     int arrayLength;         // 栈容量
 9     int stackTop;          // 栈顶
10 
11 public:
12     MyStack(int size);
13     ~MyStack();
14     bool stackEmpty();    //判断栈是否为空
15     bool stackFull();     //判断栈是否满
16     void clear();    // 清空栈
17     int stackLength();    // 已有元素的个数
18     void push(char elem); // 将元素入栈 
19     void pop(); // 清除栈头
20     char top();
21     void stackTraverse(); // 栈遍历
22 };
23 
24 MyStack::MyStack(int size)
25 {
26     arrayLength = size;
27     stack = new char[size];
28     stackTop = 0;
29 }
30 
31 
32 MyStack::~MyStack()
33 {
34     delete[] stack;
35 }
36 
37 bool MyStack::stackEmpty()
38 {
39     if (stackTop == 0)
40         return true;
41     else
42         return false;
43 }
44 
45 bool MyStack::stackFull()
46 {
47     if (stackTop >= arrayLength)
48         return true;
49     else
50         return false;
51 }
52 
53 void MyStack::clear()
54 {
55     stackTop = 0;
56 }
57 
58 int MyStack::stackLength()
59 {
60     return stackTop;
61 }
62 
63 void MyStack::push(char elem)//压栈
64 {
65     if (stackFull())
66     {
67         return;//可以改成扩容
68     }
69     stack[stackTop] = elem;
70     stackTop++;
71 }
72 
73 void MyStack::pop()//清除栈头
74 {
75     if (stackEmpty())
76         return;
77     stackTop--;
78 }
79 
80 char MyStack::top() {//返回头上的那个元素,但是不删除
81     if (stackEmpty()) {
82         cout << "栈空" << endl;
83         return false;
84     }
85     return stack[stackTop];
86 }
87 void MyStack::stackTraverse()
88 {
89     for (int i = stackTop - 1; i >= 0; i--)
90     {
91         cout << stack[i] << ",";
92     }
93     cout << endl;
94 
95 }

 

数组队列:

 1 #include<iostream>
 2 using namespace std;
 3 #define MAXSIZE 10
 4 class queue
 5 {
 6 public:
 7         queue();
 8         bool IsFull();
 9         bool IsEmpty();
10         bool EnQueue(int);
11         bool DeQueue(int&);
12 private:
13         int buf[MAXSIZE];
14         int rear;
15         int front;
16 };
17 queue::queue()
18 {
19         this->rear=0;
20         this->front=0;
21 }
22 bool queue::IsEmpty()
23 {
24         if(this->rear==this->front)
25                 return true;
26         else
27                 return false;
28 }
29 bool queue::IsFull()
30 {
31         if((this->rear+1)%MAXSIZE==this->front)
32                 return true;
33         else
34                 return false;
35 }
36 bool queue::EnQueue(int data)
37 {
38         if(IsFull())
39                 return false;
40         this->buf[this->rear]=data;
41         this->rear=(this->rear+1)%MAXSIZE;
42         return true;
43 }
44 bool queue::DeQueue(int& data)
45 {
46         if(IsEmpty())
47                 return false;
48         data=this->buf[this->front];
49         this->front=(this->front+1)%MAXSIZE;
50 }

 

//队列用数组来实现有点不舒服

posted on 2020-02-10 21:56  夜隳·依子  阅读(92)  评论(0编辑  收藏  举报