链表实现栈:具体函数实现

代码部分

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;
}
相关推荐
倒头就睡的小比特21 小时前
算法竞赛C++常用的STL
c++·算法
weilx123421 小时前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛1 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·1 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven1 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码1 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎