每天一道leetcode142-寻找链表中环的入口 分类:链表 中文链接: https://leetcode-cn.com/problems/linked-list-cycle-ii/ 英文链接 https://leetcode.com/problems/linked-list-cycle-ii/
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 说明:不允许修改给定的链表。 进阶: 你是否可以不用额外空间解决此题?
使用额外空间的思路
代码
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { HashMap<ListNode,Integer> map = new HashMap<>(); if(head == null || head.next == null) return null; while(head != null) { if(map.containsKey(head) == false) { map.put(head,1); head = head.next; }else{ return head; } } return null; } }
代码讲解
不使用额外空间的思路
代码
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { boolean flag = true; public ListNode detectCycle(ListNode head) { ListNode pHead = head; if(pHead == null || pHead.next == null) return null; ListNode pNode = judgeHasChain(pHead); if(pNode != null) { int lengthChain = 1; ListNode pNodeCopy = pNode.next; while(pNodeCopy != pNode) { lengthChain++; pNodeCopy = pNodeCopy.next; } ListNode fast = pHead; ListNode slow = pHead; int temp = 0; while(temp < lengthChain) { fast = fast.next; temp++; } while(fast != slow) { fast = fast.next; slow = slow.next; } return fast; } return null; } private ListNode judgeHasChain(ListNode pHead) { ListNode fast = pHead.next; ListNode slow = pHead; while(fast != slow) { if(fast != null && fast.next != null) { fast = fast.next; }else{ flag = false; break; } if(slow != null && slow.next != null) { slow = slow.next; }else{ flag = false; break; } if(fast == slow) { return fast; }else{ fast = fast.next; } } if(flag) return fast; return null; } }
代码讲解
本文分享自微信公众号 - 程序员乔戈里(CXYqiaogeli),作者:乔戈里qgl
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2018-11-11
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句