[LeetCode]142. Linked List Cycle II
来源:互联网 发布:汽车cd刻录软件 编辑:程序博客网 时间:2024/05/03 13:21
Problem Description
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?
[https://leetcode.com/problems/linked-list-cycle-ii/]
思路
还是用两个指针,一个快一个慢,发现有圈之后,将一个指针扔回head,然后每个指针相同速度一格格走,再次相遇的地方就是圈的起点。
设圈前面有n个格,在圈里第x个格第一次相遇,圈的长度为y。
辣么!!2*(n+x)=n+x+y
辣么!!!n=y-x
y-x就是让一个点走回圈的起点!!
n是让一个点从起点走到圈的起点!!
就酱!
Code
package Q142;public class Solution { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public static ListNode detectCycle(ListNode head) { ListNode quick=head; ListNode slow=head; int mark=0; if(head==null) return null; while(quick.next!=null&&quick.next.next!=null){ quick=quick.next.next; slow=slow.next; if(quick==slow){ mark=1; break; } } if(mark==0) return null; quick=head; while(quick!=slow){ quick=quick.next; slow=slow.next; } return slow; }// public static void main(String[] args){// ListNode a1= new ListNode(1);// ListNode a2= new ListNode(2);// ListNode a3= new ListNode(3);// ListNode a4= new ListNode(4);// ListNode a5= new ListNode(5);// ListNode a6= new ListNode(6);// ListNode a7= new ListNode(7);// ListNode a8= new ListNode(8);// a1.next=a2;// a2.next=a3;// a3.next=a4;// a4.next=a5;// a5.next=a6;// a6.next=a7;// a7.next=a8;// a8.next=a4;// System.out.print(detectCycle(a1).val);// }}
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- Codeforces Round #342 (Div. 2) 625B War of the Corporations(stl)
- 数据结构实验之链表七:单链表中重复元素的删除
- iOS-基础动画
- ansys 15 for linux 安装纪录
- C++构造函数与析构函数
- [LeetCode]142. Linked List Cycle II
- 03环信好友管理 - 添加好友(好友申请)
- hdoj2027 统计元音
- 一个通俗易懂的DP入门讲解
- 定位kernel32.dll
- 关于vmnet1~vmnet8(虚拟机下的linxu网络连接方式)
- MongoDB的用法集锦:查询篇----->持续更新中
- MySQL的SQL_NO_CACHE
- C++拷贝构造函数详解