必知C++算法之栈和队列基本操作

本秂侑毒 提交于 2020-01-23 15:10:05

1.push
2.pop
3.top
4.size
注意:遍历打印栈空间时不要用for循环size(),因为栈的size()时在改变的,输出会少很多数据
    cout << "s.size()=" << s.size() << endl;
	for(int i = 0; i < s.size(); ++i) {
		cout << s.size() << endl;
		cout << s.top() << " ";
		s.pop();
	}
用while+empty()即可:
    while (!s.empty()) {
            cout << s.top() << " ";
            s.pop();
        }


栈的一些操作:

//获取栈底元素
int getBottomNum(stack<int>& stack) {
	if (stack.empty())
		return -1;
	int res = stack.top();
	stack.pop();
	if (stack.empty()) {
		return res;
	}
	else {
		int last = getBottomNum(stack);
		stack.push(res);
		return last;
	}
}

void test01() {
	//移除栈底元素
	stack<int> stack;
	for (int i = 2; i < 10; ++i) {
		stack.push(i);
	}
	cout << getBottomNum(stack) << endl;
}

//逆序栈空间
void ReverseStack(stack<int> &stack) {
	if (stack.empty()) {
		return;
	}
	int i = getBottomNum(stack);
	ReverseStack(stack);
	stack.push(i);
}

void test02() {
	stack<int> stack;
	for (int i = 0; i < 5; ++i) {
		stack.push(i);
	}
	ReverseStack(stack);
	for (int i = 0; i < 5; ++i) {
		cout << stack.top() << " ";
		stack.pop();
	}
}
//给栈空间数据排序
void StackSort(stack<int>& s){
	if (s.empty())
		return;
	stack<int> help;
	int res = 0;
	int ans = 0;
	if (help.empty()) {
		res = s.top();
		s.pop();
		help.push(res);
	}
	while (!s.empty()) {
		res = s.top();
		s.pop();
		if (res <= help.top()) {
			help.push(res);
		}
		else {
			while ((!help.empty()) && res > help.top()) {
				ans = help.top();
				help.pop();
				s.push(ans);
			}
			help.push(res);
		}
	}
	while (!help.empty()) {
		res = help.top();
		help.pop();
		s.push(res);
	}
}

队列

1.push
2.pop
  • 双端队列为首尾部都可以压入和弹出元素
  • 优先级队列为根据元素的优先级值,决定元素的弹出顺序。
  • 优先级队列的结构为堆结构,并不是线性结构。******
题目:(普通解法时间复杂度O(N*w))最优解时间复杂度为O(N)
//运用了双端队列qmax={}
有个整型数组arr和一个大小为w的窗口,从左滑倒右边。
列如[4,3,5,4,3,3,6,7],w=3
窗口滑动中3个数最大值返回出来
最终返回[5,5,5,4,6,7]
深度优先遍历(DFS:Depth-first search)和宽度优先遍历(BFS:Breadth-First-Search)

深度优先遍历:可以用栈来实现

宽度优先遍历:可以用队列来实现

拓展:

平时使用的递归函数实际上用到了提供的函数系统栈,
递归的过程可以看做递归函数依次进入函数栈的处理过程,
所有用递归函数可以做的过程都一定可以用非递归的方式实现。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!