数据结构-链表
141 环形链表
unordered_set<ListNode*> seen;
while(head!=nullptr){
if(seen.count(head)){
return true;
}
seen.insert(head)
head=head->next;
}
return false;
}
定义
unordered_set<int> c1//创建哈希表
容量操作
c1.empty();//判断是否为空
c1.size();//获取元素个数
c1.max_size();//获取最大存储量
迭代器操作
//返回头迭代器
unordered_set<int>::iterator ite_begin=c1.begin();
//返回尾迭代器
unordered_set<int>::iterator ite_end=c1.end();
//槽迭代器
unordered_set<int>::iterator local_iter_begin=c1.begin();
unordered_set<int>::iterator local_iter_end=c1.end();
基本操作
//查找函数find通过给定主键查找元素
unordered_set<int>::iterator find_iter=c1.find(1)
//value出现的次数count返回匹配给定主键元素的个数
c1.count(1);
//返回元素在哪个区域equal_range,返回值匹配给定搜索值的元素组成的范围
pair<unordered_set<int>::iterator,
unordered_set<int>::iterator>pair_equal_range = c1.equal_range(1)
//插入函数emplace
c1.emplace(1);
//插入函数emplace_hint()使用迭代器
c1.emplace_hint(ite.begin,1);
//插入函数insert
c1.insert(1);
//删除erase
c1.erase(1);
//清空clear;
c1.clear();
//交换swap
c1.swap(c2);
21 合并两个有序链表
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* list3 = new ListNode(-1);
ListNode* head= list3;
while(list1!=nullptr&&list2!=nullptr){
if(list1->val<list2->val){
head->next=list1;
list1=list1->next;
}else{
head->next=list2;
list2=list2->next;
}
head=head->next;
}
head->next = list1 == nullptr ? list2:list1;
return list3->next;
}
};
203 移除链表元素
此题目可能移除表头元素,所以初始时创建Node空表头节点进行操作。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
struct ListNode* Node=new ListNode(0,head);
struct ListNode* temp=Node;
while(temp->next!=NULL){
if(temp->next->val==val){
temp->next=temp->next->next;
}else{
temp=temp->next;
}
}
return Node->next;
}
};
- 本文链接:https://archer-lan.github.io/2022/03/08/LeetCode%20%E5%88%B7%E9%A2%98%E6%97%A5%E8%AE%B0-DAY3/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。