题目描述: 给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。文章源自随机的未知-https://sjdwz.com/11114.html
Map集合解法
思路: 创建一个map集合,key为节点,value为地址值,因为ListNode没有重写toString()方法,所以用toString()方法返回的内容作为value。 如果map中存在当前节点的toString()方法返回的内容,则存在环。文章源自随机的未知-https://sjdwz.com/11114.html
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
Map<ListNode,String> map = new HashMap<ListNode,String>();
while(head != null){
if(map.containsValue(head.toString())){
return true;
}
else{
map.put(head,head.toString());
head = head.next;
}
}
return false;
}
}
提交结果截图:
文章源自随机的未知-https://sjdwz.com/11114.html
快慢指针解法
分析: 将slow指针指向head; 将fast指针指向head.next; 在循环的过程中slow走一步,fast走两步,如果存在环,则slow和fast一定会相遇,如本例子中:slow在1处,fast在2处;然后slow走一步,到2处,fast走两步,到4处;slow到3处,fast到3处,slow和fast相遇。 代码如下:文章源自随机的未知-https://sjdwz.com/11114.html
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while(fast != null){
if(slow == fast){
return true;
}
slow = slow.next;
fast = fast.next;
if(fast != null)
fast = fast.next;
}
return false;
}
}
对代码的解释: 1、如果head为空,则不是环,返回false; 2、如果fast不为空,则进入循环体;否则退出循环,无环,返回false; 3、如果slow和fast指向的节点相同,则存在环,返回true; 4、slow向后移动一个节点; 4、fast向后移动一个节点,如果fast不为空,再向后移动一个节点(不能直接移动两个节点,否则会报空指针异常);转2。 提交结果截图:
由图可知,快慢指针方法更好一些。文章源自随机的未知-https://sjdwz.com/11114.html
欢迎关注
扫下方二维码即可关注: 文章源自随机的未知-https://sjdwz.com/11114.html