8.27 刷题第三天
141. 环形链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set <ListNode*> seen;//哈希表实现
while(head!=NULL){
if(seen.count(head)){
return true;
}
seen.insert(head);
head=head->next;
}
return false;
}
};
C++ set与map、unordered_map、unordered_set与哈希表
set和map都部分采用了红黑树结构,unordered_map和unordered_set采用哈希表结构,主要特别是没有自动排序。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//快慢指针
if(head==NULL||head->next==NULL){
return false;
}
ListNode* fast = head->next;
ListNode* slow = head;
while(slow!=fast){
if(fast==NULL||fast->next==NULL){
return false;
}
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};
1h 困
2. 两数相加
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int temp=0;
ListNode *l3=nullptr;
ListNode *head=nullptr;
int n1,n2;
while(l1!=nullptr||l2!=nullptr){
n1=l1?l1->val:0;
n2=l2?l2->val:0;
temp=temp+n1+n2;
if(l1){
l1=l1->next;
}
if(l2){
l2=l2->next;
}
if(!l3){
head=l3=new ListNode(temp%10);
}else{
l3->next=new ListNode(temp%10);
l3=l3->next;
}
temp=temp/10;
}
if(temp>0){
l3->next=new ListNode(temp);
}
return head;
}
};
链表
//创建链表
ListNode *l3=nullptr;
//增加节点
l3->next=new ListNode(XXX);
//遍历
while(l!=nullptr){
l=l->next;
}
//查看是否为空
if(!l)
1h