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

代码部分

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;
}
相关推荐
端平入洛7 小时前
delete又未完全delete
c++
端平入洛1 天前
auto有时不auto
c++
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
qq_454245032 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA2 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法