左程云算法学习《个人笔记》C++版4、哈希表、链表、原地反转链表

哈希表的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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值