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

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)

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

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

拓展:

平时使用的递归函数实际上用到了提供的函数系统栈,
递归的过程可以看做递归函数依次进入函数栈的处理过程,
所有用递归函数可以做的过程都一定可以用非递归的方式实现。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值