哈希表的stl用法insert,count,find,erase,遍历
#include <iostream>
#include <queue>
#include <algorithm>
#include<unordered_map>
using namespace std;
int main()
{
unordered_map<int,int> mp;
//①插入数据
mp[1]=2;
mp[2]=3;
//②插入数据
mp.insert({5,6});
//③插入数据(pair的用法)
pair<int,int> a = {8,7};
pair<int,int> b(19,6);
mp.insert(b);
//修改数据
mp[1]=8;
//①查找数据
auto it=mp.find(2);
//②查找数据
cout<<mp.count(19)<<endl;
//删除数据
mp.erase(1);
//①遍历
for(auto map1:mp){
cout<<map1.first<<" "<<map1.second<<endl;
}
//②遍历
for(auto it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
cout<<mp.size();
return 0;
}
原地反转链表,
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(){}
ListNode(int x){val=x;next=NULL;}
ListNode(int x,ListNode*head){val=x,next=head;}
};
ListNode *reverse(ListNode *head){
ListNode *pre=head;
ListNode *cur=head;
ListNode *nex=head->next;
while(nex!=NULL){
cur->next=nex->next;
nex->next=pre;
pre=nex;
nex=cur->next;
}
return pre->next;//第一个节点为哨兵节点,所以返回pre->next;
}
int main(){
ListNode *L=new ListNode(0);//当做头结点或者哨兵,这样可以减少一些判断为空的代码量
ListNode *L1=new ListNode(5,L);
ListNode *L2=new ListNode(8,L1);
ListNode *L3=new ListNode(2,L2);
ListNode *L4=new ListNode(4,L3);
ListNode *res=reverse(L);
ListNode *dummy=res;
while(res!=NULL){
cout<<res->val<<" ";
res=res->next;
}
ListNode *res1=reverse(dummy);
while(res1!=NULL){
cout<<res1->val<<" ";
res1=res1->next;
}
}