链表-Linked List Cycle II(判断一个链表是否有环)
来源:互联网 发布:java软件开发培训机构 编辑:程序博客网 时间:2024/05/30 23:05
问题描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思考:
参考了网上的方法,判断一个单向链表是否有环,如果没有返回空,如果有返回这个环的开始处,也就是和前面直线的焦点。
画出图:从开始的节点分别放慢指针和快指针两个指针,快的每次走两步,慢的每次走一步。
类似时针分针,如果链表有环,两个指针一定会在环中相遇,此时即可推断:
2s = nc+s,
s=a+x,
=> a+x=nc,
a=nc-x,
a=(n-1)c+c-x其中n-1为整数圈数,这个意思是当两个指针相遇的时候,把快指针放回头节点,慢指针在原处,快指针每次就只走一步了,此时快指针走到环开始的地方时,慢指针走了剩余的半圈加(n-1)个整圈,以此找出环开始处。
代码(java):
public class LinkedListCycleII {static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public ListNode detectCycle(ListNode head) { ListNode slow,fast;//只有一个节点或者就没有if(head == null || head.next == null){return null;}//正式开始slow = head;fast = head;while(true){if(fast == null || fast.next == null){return null;}slow = slow.next;fast = fast.next.next;if(slow == fast){break;}}slow = head;while(true){if(slow == fast){break;}slow = slow.next;fast = fast.next;}return slow;}}
0 0
- 链表-Linked List Cycle II(判断一个链表是否有环)
- 判断链表是否有环 Linked List Cycle, Linked List Cycle II
- LeetCode OJ 之 Linked List Cycle II(判断链表是否有环 - 二)
- 【leetcode】Linked List Cycle II,判断链表是否有环
- 判断链表是否有环 Linked List Cycle
- Linked List Cycle --判断链表是否有环
- leetcode--Linked List Cycle--判断链表是否有环
- Linked List Cycle 判断链表是否有环
- Linked List Cycle:判断链表是否有环
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- LeetCode | Linked List Cycle(判断链表是否有环)
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- 141. Linked List Cycle (判断单链表中是否有环)
- 141.Linked List Cycle (判断一个单链表是否有环)
- Linked List Cycle 判断链表是否有环,如果有环,找到环的入口
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- webservice报错NullPointerException的解决方法
- config a writable directory on apache
- Protege初学者
- django + uwsgi + nginx 配置
- spring注解 repository,component,service,controller
- 链表-Linked List Cycle II(判断一个链表是否有环)
- Ubuntu下DHCP服务器安装与配置
- nyoj139
- depends-on的用法
- Linux下多线程编程实例解析
- 增加HTML元素
- LeetCode之10 --- Regular Expression Matching
- Android OpenGL ES 开发教程 从入门到精通
- 拖延心理学