博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lintcode:带环链表
阅读量:7295 次
发布时间:2019-06-30

本文共 1595 字,大约阅读时间需要 5 分钟。

带环链表

给定一个链表,判断它是否有环。

解题

定义两个指针p1 p2

p1每次向前走一步

p2每次向前走两步

当p2能赶上p1的时候说明有环

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @return: True if it has a cycle, or false     */    public boolean hasCycle(ListNode head) {          // write your code here        if(head == null || head.next == null)            return false;        ListNode p1 = head;        ListNode p2 = head;        p2 = p2.next;        while(p2.next!=null && p2.next.next!=null){            if(p1 == p2){                return true;            }            p1 = p1.next;            p2 = p2.next.next;        }        return false;    }}
Java Code

 

1 """ 2 Definition of ListNode 3 class ListNode(object): 4  5     def __init__(self, val, next=None): 6         self.val = val 7         self.next = next 8 """ 9 class Solution:10     """11     @param head: The first node of the linked list.12     @return: True if it has a cycle, or false13     """14     def hasCycle(self, head):15         # write your code here16         if head == None or head.next == None:17             return False18         slow = head19         fast = head20         fast = fast.next21         while fast.next!=None and fast.next.next!=None:22             if fast == slow:23                 return True24             else:25                 slow = slow.next26                 fast = fast.next.next27         return False
Python Code

 

转载地址:http://kmgjm.baihongyu.com/

你可能感兴趣的文章
Python3.7安装PyQt5的方法
查看>>
Zoj 3781(构造)
查看>>
One error related to msxml4.dll (0x800C0014)
查看>>
“爆打”团队阿尔法发布 以及 第四周任务
查看>>
【堆】bzoj1293 [SCOI2009]生日礼物
查看>>
JavaScript的异步运行机制
查看>>
centos7安装HTTPS协议
查看>>
GNS3 模拟icmp端口不可达
查看>>
hdu 5677 ztr loves substring 多重背包
查看>>
WCF学习
查看>>
django 基础进 COOKIE
查看>>
[Java 8] (10) 使用Lambda完成函数组合,Map-Reduce以及并行化
查看>>
@EnableWebMvc
查看>>
eclipse中输入的中文为繁体的问题
查看>>
.NET跨平台:在Linux Ubuntu上编译coreclr/corefx/dnx(20150617)
查看>>
[CQOI2016]手机号码
查看>>
Eclipse CDT 配置C /C ++ 标准库 (UBUNTU 12 )
查看>>
面霸吕国栋之:整理的一些面试题
查看>>
转 Python爬虫入门五之URLError异常处理
查看>>
转 Python执行系统命令的方法
查看>>