栈的定义与运算

  1. 栈是只允许在线性表的一段进行插入和删除的线性表。表中值允许插入和删除的一段称为栈顶命令一段称为栈底。

    1. 由于只能在栈顶进行插入和删除操作,使得后进栈的元素先出栈,先进栈的元素后出栈,所以栈是一种后进先出(Last In First Out,简称LIFO)的数据结构。有关栈的应用都是基于这一特性。
  2. 栈的操作通常称为入栈或进栈,其删除操作称为出栈或退栈。当栈中五元素是,称为空栈。

有关栈的基本操作主要有以下几种:

1. 栈的初始化操作,即建立一个空栈S
 2. 判空栈操作,弱S为空栈,返回一个真值
 3. 进栈操作,在S栈顶插入一个元素X
 4. 出栈操作,若栈S不空,则取栈顶元素(栈顶元素不删除)。 

栈的顺序存储结构(又称为顺序栈)类似于线性表的顺序存储结构。

队列

双队列实现栈的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class MyStack {
queue<int> queue1;
queue<int> queue2;
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
void push(int x) {
queue2.push(x);
while (!queue1.empty()) {
queue2.push(queue1.front());
queue1.pop();
}
swap (queue1,queue2);
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int r = queue1.front();
queue1.pop();
return r;
}

/** Get the top element. */
int top() {
int r = queue1.front();
return r;
}

/** Returns whether the stack is empty. */
bool empty() {
return queue1.empty();
}
};

/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/

环形队列

环形队列(头就是尾,尾就是头)