赞
踩
原题链接:环形链表
题目:给定一个链表的头节点,判断该链表是否有环
代码:
- public boolean hasCycle(ListNode head) {
- Set<ListNode> set = new HashSet<>();
- while (head != null){
- if (!set.add(head)){
- return true;
- }
- head = head.next;
- }
- return false;
- }

如上图,快慢指针slow,fast分别指向head,head.next节点,若慢指针追上快指针,则证明该链表存在环
代码:
- public boolean hasCycle(ListNode head) {
- if(head == null || head.next == null) return false;
- ListNode slow = head;
- ListNode fast = head.next;
- while (fast != null && fast.next != null){
- if (slow == fast) return true;
- slow = slow.next;
- fast = fast.next.next;
- }
- return false;
- }
进一步找出环形链表中环开始的第一个节点?
原题链接:环形链表环开始的节点
代码:
- public ListNode detectCycle(ListNode head) {
- Set<ListNode> set = new HashSet<>();
- while (head != null){
- if (!set.add(head)){
- return head;
- }
- head = head.next;
- }
- return null;
- }

如上图,当慢指针,快指针slow,fast第一次在b节点相遇,此时slow指向head指针,fast指向下一节点,下一次相遇时即为a节点
两指针在b节点相遇则代表head到b节点的距离等于b节点绕环一圈到b节点距离,两段距离同时减去a到b的距离即相等,即head到a节点距离等于b到a节点距离,即快慢指针此时速度相同则可同时到达a节点
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。