专栏文章

数据结构的包装整理

个人记录参与者 1已保存评论 0

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
0 条
当前快照
1 份
快照标识符
@miogur9e
此快照首次捕获于
2025/12/02 18:59
3 个月前
此快照最后确认于
2025/12/02 18:59
3 个月前
查看原文

栈(stack)

代码

note
底层使用数组实现,非常快。所有函数的时间复杂度为 O(1)O(1)
C
#include<bits/stdc++.h>
using namespace std;

template<typename T,int SIZE> 
class Stack {
	private:
		T stk[SIZE+5];
		int idx;
	public:
		Stack():idx(0){}
		bool empty() const {
			return !idx;
		}
		bool full() const {
			return idx==SIZE;
		}
		int size() const {
			return idx;
		} 
		T top() const {
        	if(empty()) {
				throw out_of_range("Stack is empty.");
			}
			return stk[idx];
		}
		void push(T x) {
			if(full()) {
				throw out_of_range("Stack is full.");
			}
			stk[++idx]=x;
		} 
		void pop() {
			idx--;
		}
		void clear() {
			idx=0;
		}
}; 

使用说明

C
Stack<typename,SIZE> stk;
其中 typename 为任意数据类型,SIZE 为栈的最大大小(通常根据题目设定)。
返回类型代码操作
bool\text{bool}stk.empty()判断栈是否为空
bool\text{bool}stk.full()判断栈是否已满
bool\text{bool}stk.size()返回栈中元素个数
typenametypenamestk.top()返回栈顶元素
void\text{void}stk.push(x)在栈顶加入一个元素(如果栈已满抛出异常)
void\text{void}stk.pop()删除栈顶元素(如果栈为空抛出异常)
void\text{void}stk.clear()删除栈中所有元素
 \

队列(queue)

代码

note
底层使用循环队列,数组实现,非常快。所有函数的时间复杂度为 O(1)O(1)
C
#include<bits/stdc++.h>
using namespace std;

template<typename T,int SIZE>
class Queue {
	private:
		T q[SIZE+5];
		int front,back,cnt;
	public:
	    Queue():front(0),back(0),cnt(0){}
	    void push(T value) {
	        if(full()) {
	            throw overflow_error("Queue is full.");
	        }
	        q[back]=value;
	        back=(back+1)%SIZE;
	        cnt++;
	    }
	    void push() {
	        if(empty()) {
	            throw underflow_error("Queue is empty.");
	        }
	        front=(front+1)%SIZE;
	        cnt--;
	    }
	    T front() const {
	        if (empty()) {
	            throw underflow_error("Queue is empty");
	        }
	        return q[front];
	    }
	    bool empty() const {
	        return cnt==0;
	    }
	    bool full() const {
	        return cnt==SIZE;
	    }
	    int size() const {
	        return cnt;
	    }
	    void clear() {
	    	front=back=cnt=0;
	    }
};

使用说明

C
Queue<typename,SIZE> q;
其中 typename 为任意数据类型,SIZE 为栈的最大大小(通常根据题目设定)。
返回类型代码操作
bool\text{bool}q.empty()判断队列是否为空
bool\text{bool}q.full()判断队列是否已满
bool\text{bool}q.size()返回队列中元素个数
typenametypenameq.front()返回队头元素
void\text{void}q.push(x)在队尾加入一个元素(如果队列已满抛出异常)
void\text{void}q.pop()删除队头元素(如果队列为空抛出异常)
void\text{void}q.clear()删除队列中所有元素
 \

评论

0 条评论,欢迎与作者交流。

正在加载评论...