代码部分
cpp
template<typename T>
Stack<T>::~Stack() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
template<typename T>
void Stack<T>::push(T element) {//头插法
Node* newNode = new Node(element);
newNode->next = head;
head = newNode;
size++;
}
template<typename T>
T Stack<T>::pop() {
if (head == NULL) {
throw underflow_error("Stack is empty!");
}
T result = head->data;
Node* temp = head;
head = head->next;
delete temp;
size--;
return result;
}
template<typename T>
T Stack<T>::top() const {
if (head == NULL) {
throw underflow_error("Stack is empty!");
}
return head->data;
}
template<typename T>
int Stack<T>::getSize() const {
return size;
}
1.析构函数
首先是模板声明和函数声明,析构无需返回值,所以为void,析构函数就是释放掉存放链表时申请的内存,在一个while循环里面,利用temp暂存头节点,然后通过不断偏移头节点,直到最终释放所有的内存。
cpp
template<typename T>
Stack<T>::~Stack() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
2.入栈
然后是入栈,函数返回值为void,像插入一样,无需返回值,然后就是带<T>的作用域,作为类模板的成员函数实现,参数列表为T类型的元素,代表待插入的元素,然后函数内部实现,我们采用头插法,将插入元素作为新的头节点,就如同插入位置为0一样,首先定义一个结构体指针指向一个新的结构体的内存空间,内存空间的作用域初始化为element,然后让这个新的节点指向头节点,然后将这个新的节点置为头节点,同时让链表长度加一。
cpp
template<typename T>
void Stack<T>::push(T element) {//头插法
Node* newNode = new Node(element);
newNode->next = head;
head = newNode;
size++;
}
3.出栈:返回栈顶元素并删除栈顶元素
然后是出栈,首先是模板声明和函数声明,函数返回值为T,由于要我们返回栈顶元素,函数名为pop,然后函数实现部分,我们首先判断链表是否为空,因为要返回栈顶元素和删除,这里如果为空就会报错了,所以我们要做一个判断语句,如果为空,则要抛出异常。然后定义T类型变量暂存栈顶节点的数据域,也就是栈顶元素,然后定义结构体指针暂存头节点,紧接着让头节点偏移,指向它的后继,然后删除栈顶节点,同时让栈的长度减一,最后返回栈顶元素。
cpp
template<typename T>
T Stack<T>::pop() {
if (head == NULL) {
throw underflow_error("Stack is empty!");
}
T result = head->data;
Node* temp = head;
head = head->next;
delete temp;
size--;
return result;
}
4.返回栈顶元素
首先是模板声明和函数声明,函数返回值类型为T,由于我们要返回栈顶元素,然后函数名为top,代表栈顶,后面的const是为了保证这个函数不会改变栈本身,然后函数内部实现,首先判断栈是否为空,空则抛出异常,然后返回头节点对应的元素,即栈顶元素。
cpp
template<typename T>
T Stack<T>::top() const {
if (head == NULL) {
throw underflow_error("Stack is empty!");
}
return head->data;
}
5.求栈的长度
首先是模板声明和函数声明,函数返回值为int,由于要返回栈的长度,然后函数名为getSize,然后函数名后面带上const,确保函数不会改变栈本身,函数内部返回长度即可。
cpp
template<typename T>
int Stack<T>::getSize() const {
return size;
}
6.主函数实现
cpp
int main() {
Stack<int> st;
st.push(4);
st.push(5);
st.push(6);
cout << st.top() << endl;
st.pop();
cout << st.getSize() << endl;
return 0;
}