力扣刷题day3

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值