STL-栈,队列,优先队列

STL-栈

#include<stdio.h>
#include<stack>
using namespace std;


struct node{
	int value;
	struct node * next;
};
int main(){
	stack<int> s;
	s.push(5);
	s.push(6);
	while(!s.empty()){
		int x = s.top();
		printf("%d %d\n",x,s.size());
		s.pop();
	}
	
	stack<struct node>root;
	struct node x,y;
	x.value = 3;
	y.value = 4;
	root.push(x);
	root.push(y);
	while(!root.empty()){
		printf("%d %d\n",root.top().value,root.size());
		root.pop();
	}
	return 0;
} 

STL-队列

#include<stdio.h>
#include<queue>
using namespace std;

struct node{
	int value;
	struct node  * next;
};
int main(){
	queue<struct node>root;
	struct node x,y,z;
	x.value = 3;
	y.value = 4;
	z.value = 5;
	root.push(x);
	root.push(y);
	root.push(z);
	
	while(!root.empty()){
		struct node front = root.front();
		struct node back = root.back();
		root.pop();
		printf("front:%d\t",front.value);
		printf("back:%d\t",back.value);
		printf("size:%d\n",root.size());
	}
	return 0;
}

STL-优先队列

#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
struct cmp{
    bool operator ()(int &a,int &b){
        return a>b;//a的优先级小于b的优先级 条件是a<b,因此,这种情况下数值越小,优先级越小 ;a的优先级小于b的优先级 条件是a>b,因此,这种情况下数值越大,优先级越小 
    }
};
struct node{
    int value;
	struct node * next;
    friend bool operator < (node a, node b){
        return a.value > b.value; //同理,a的优先级小于b的优先级,条件是a.value > b.value 
    }
};

//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
int main(){
	priority_queue<int>q1;
	q1.push(3);
	q1.push(1);
	q1.push(5);
	while(!q1.empty()){
		printf("%d %d\n",q1.top(),q1.size());
		q1.pop();
	}
	printf("------\n");
	priority_queue<int,vector<int>,cmp>q2;
	q2.push(3);
	q2.push(1);
	q2.push(5);
	while(!q2.empty()){
		printf("%d %d\n",q2.top(),q2.size());
		q2.pop();
	}
	printf("------\n");
	priority_queue<struct node>q3;
	struct node x,y,z;
	x.value = 2;
	y.value = 5;
	z.value = 1;
	q3.push(x);
	q3.push(y);
	q3.push(z);
	while(!q3.empty()){
		struct node p = q3.top();
		printf("%d %d\n",p.value,q3.size());
		q3.pop();
	}
	return 0;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值