1106-leetcode142环形链表II 和160. 相交链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(!head || !head->next) return NULL;
        ListNode *slow=head,*fast=head,*flag=head;
  
        while(true){
            slow=slow->next;
            fast=fast->next;
            if(!fast){return NULL;}
            fast=fast->next;
            if(!fast){return NULL;}
            if(slow==fast){break;}
        }
        while(true){
            if(slow==flag){return slow;}
            slow=slow->next;
            flag=flag->next;
         
            if(!flag){return NULL;}
        }
    }
};

**

每次移动都需要考虑 链表是否越界了

c++的是NULL和true

**
单链表的中点也可以用快慢指针解决

160. 相交链表

**(用额外的空间)哈希集合存储相交的节点
set的count()只返回0/1 就是出现或没出 因为没有重复元素
erase(iterator) ,删除定位器iterator指向的值
erase(first,second),删除定位器first和second之间的值
erase(key_value),删除键值key_value的值
find() ,返回给定值值得定位器,如果没找到则返回end()
lower_bound(key_value) ,返回第一个大于等于key_value的定位器
upper_bound(key_value),返回最后一个大于等于key_value的定位器

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *p1=headA,*p2=headB;
        set<ListNode *> s;
        while(p1){
            s.insert(p1);
            p1=p1->next;
        }
        while(p2){
            if(s.count(p2)){return p2;}
            else{p2=p2->next;}
        }
        return NULL;
    }
};

(不用额外空间)两个指针 将题目转化为 链表是否有环 或者 将两个表接在一起**

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *p1=headA,*p2=headB;
        while(p1!=p2){
            if(!p1){p1=headB;}
            else{p1=p1->next;}
            if(!p2){p2=headA;}
            else{p2=p2->next;}
        }
        return p1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值