当前位置: 首页 > news >正文

【数据结构篇】~链表算法题3(环形链表)

链表算法题3(环形链表)

  • 环形链表的证明
  • 1. 环形链表I​
    • 1) 思路
    • 2)代码实现
  • 2. 环形链表II​
    • 1) 思路1
    • 1) 思路2
    • 2)代码实现

请添加图片描述

环形链表的证明

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

1. 环形链表I​

在这里插入图片描述

https://leetcode.cn/problems/linked-list-cycle/description/

1) 思路

在这里插入图片描述

判断链表是否带环,还是要使用快慢双指针,如果带环那他们一定在环中相遇,如果没带环那么就返回false

2)代码实现

typedef struct ListNode ls;
bool hasCycle(struct ListNode *head) {ls*slow=head,*fast=head;//开始循环while(fast && fast->next)//分为奇数偶数两种情况所以要fast&&fast->next{slow=slow->next;fast=fast->next->next;if(slow==fast)return true;}return false;   
}

2. 环形链表II​

https://leetcode.cn/problems/linked-list-cycle-ii/description/​

在这里插入图片描述
在这里插入图片描述

1) 思路1

找到相遇节点,然后把相遇节点的next指针置为newnode,再把meet->next置为空,这时再找入环节点就可以转化为找相交链表的相交节点

1) 思路2

找到相遇节点后然后开时循环,让相遇节点和头节点同时同步走,直到两个指针相遇时,就找到了入环节点

2)代码实现

typedef struct ListNode lsnode;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{lsnode*l1=headA;lsnode*l2=headB;int sizea=0;int sizeb=0;while(l1){++sizea;l1=l1->next;      }while(l2){++sizeb;l2=l2->next;     }//计算a和b的长度,让长的先走差值步,到同一起点上lsnode* plong = headA;lsnode* pshort = headB;if(sizeb>sizea){plong= headB;pshort=headA;}int gap=abs(sizea-sizeb);while(gap--){plong = plong -> next;}//开始比较while(plong && pshort){//这里比较地址,如果比较值得话有问题if(plong == pshort){ return pshort;}//同步走plong=plong->next;pshort=pshort->next;    }return NULL;   
}
struct ListNode *detectCycle(struct ListNode *head) 
{lsnode*slow=head,*fast=head;while(fast && fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast){lsnode*meet=slow;//相遇节点lsnode*newhead=meet->next;meet->next=NULL;//变为了相交链表找相交节点return getIntersectionNode(head,newhead);}       }  return NULL;
}```c
typedef struct ListNode  lsnode;
struct ListNode *detectCycle(struct ListNode *head) 
{lsnode*slow=head,*fast=head;while(fast && fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast){lsnode*meet=slow;//相遇节点while(head!=meet){head=head->next;meet=meet->next;}return meet;}      }  return NULL;   
}

http://www.mrgr.cn/news/29080.html

相关文章:

  • 【时时三省】linux应用层开发经验总结
  • 【计算机基础】关于存储的各种概念
  • 《沈阳体育学院学报》
  • 【每日一题】LeetCode 2332.坐上公交的最晚时间(数组、双指针、二分查找、排序)
  • 笔记:BLIP源码之(2)模型是如何定义的
  • 机器学习、计算机视觉与NLP:从基础到深度学习的综合指南
  • Android 微信,手机文件管理,通过自己软件打开
  • 网络安全-LD_PRELOAD,请求劫持
  • 【揭秘Java】线程安全中的有序性之谜
  • 线程池夺命十四问
  • 560. 和为 K 的子数组
  • Maya---机械模型制作
  • vs2022快捷键异常解决办法
  • 《Google软件测试之道》笔记
  • 大厂校招:唯品会Java面试题及参考答案
  • 力扣题解815
  • 星火AI-智能PPT生成 API 文档
  • Python 课程15-PyTorch
  • SAP到底是谁的系统?business or IT?
  • IDEA 2024.3 EAP新特征早览!