- 什么是栈呢?
栈是一种限制了插入和删除只能在一个位置上进行的表。
- 那这个位置又是什么呢?
这个位置就是表的末端,我们称之为栈顶。
- 栈的基本操作是什么?
无非就是压栈和出栈
- 栈的具体实现
由于栈是一种表,也是一种模型,个人认为,这种模型的主要特点就是先进后出,也称为 LIFO
。因此任何能实现一个表的方法都能实现一个栈。而常见于书本上的两种:一个是数组实现,一个是链表实现。
- 栈的数组实现(c++简略版)
#include <iostream>
using namespace std;
template<class T>
class Stack {
public:
Stack();
Stack(int capacity);
Stack(const Stack& other);
void push(T& item);
T top() const;
void pop();
bool empty() const;
bool full() const;
~Stack();
private:
T* array;
int count, capacity;
};
template<class T>
Stack<T>::Stack() {
array = NULL;
count = 0;
capacity = 1000;
}
template<class T>
Stack<T>::Stack(int capacity) {
array = NULL;
count = 0;
this.capacity = capacity;
}
template<class T>
Stack<T>::Stack(const Stack& other) {
if (array) delete[] array;
this.count = other.count;
this.capacity = other.capacity;
array = new T[this.capacity];
for (int i = 0; i < this.count; i++) array[i] = other.array[i];
}
template<class T>
void Stack<T>::pop() {
if (count > 0) count--;
}
template<class T>
void Stack<T>::push(T& item) {
if (count >= capacity) return;
array[count++] = item;
}
template<class T>
T Stack<T>::top() const {
if (!empty())
return array[count - 1];
}
template<class T>
bool Stack<T>::empty() const {
return count == 0;
}
template<class T>
bool Stack<T>::full() const {
return count == full;
}
template<class T>
Stack<T>::~Stack() {
delete[] array;
}
- 栈的链表实现(c++简略版)
#include <iostream>
using namespace std;
template<class Node_item>
struct Node {
Node_item entry;
Node<Node_item>* next;
Node();
Node(Node_item a);
};
template<class Node_item>
Node<Node_item>::Node() {
next = NULL;
}
template<class Node_item>
Node<Node_item>::Node(Node_item a) {
entry = a;
next = NULL;
}
template<class T>
class Stack {
public:
Stack();
Stack(const Stack& other);
void push(T& item);
T Top() const;
void pop();
bool empty() const;
~Stack();
private:
Node<T>* top;
};
template<class T>
Stack<T>::Stack() {
top = NULL;
}
template<class T>
Stack<T>::Stack(const Stack& other) {
while(top) pop();
Node<T>* temp = other.top;
while(temp) {
Node<T>* cur = new Node<T>(temp->entry);
cur->next = NULL;
if (top) cur->next = top;
top = cur;
temp = temp->next;
}
}
template<class T>
void Stack<T>::pop() {
if (top) {
Node<T>* next = top->next;
delete top;
top = next;
}
}
template<class T>
void Stack<T>::push(T& item) {
Node<T>* new_node = new Node<T>(item);
new_node->next = NULL;
top = new_node;
}
template<class T>
T Stack<T>::Top() const {
if (top != NULL) {
return top->entry;
}
}
- 差不多了,栈是数据结构的第一站,应该也是我最熟悉的一个内容了。上面的代码是临时敲…额,不对,根据我的web老师说,代码是写出来的,这样更显得优雅,所以是我临时写出来的。如果有错,可以评论,我会在有空的时候立刻回复。大家一起学习进步嘛