LeetCode -- Linked List Cycle II
来源:互联网 发布:淘宝保证金计划5000元 编辑:程序博客网 时间:2024/06/05 18:23
题目描述:
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?
判断链表是否有环,如果存在,返回环起始节点;如果不存在,返回Null。
思路:
1. 使用快慢指针的方法找到环的位置。
2. 如果找到了环,慢指针回到起点,快慢指针每次各走一步,下一次相遇的位置就是环的起点。
实现代码:
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?
判断链表是否有环,如果存在,返回环起始节点;如果不存在,返回Null。
思路:
1. 使用快慢指针的方法找到环的位置。
2. 如果找到了环,慢指针回到起点,快慢指针每次各走一步,下一次相遇的位置就是环的起点。
实现代码:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode DetectCycle(ListNode head) { if(head == null){ return null; } var p = head; var q = head; var found = false; while(p != null && q != null && q.next != null && !found){ var t = q; p = p.next; q = q.next.next; if(ReferenceEquals(p,q)){ found = true; } } if(!found){ return null; } // p start from head again // and q standing where it is // next time they meet point is where cycle starts from p = head; while(!ReferenceEquals(p, q)){ p = p.next; q = q.next; } return q; }}
1 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- js几秒以后倒计时跳转示例
- Android setOnItemLongClickListener setOnItemClickListener 同时触发解决
- 计算机基础知识(软件开发和编程语言简介)
- JAVA将一个字符串反向颠倒
- 大数加法模板
- LeetCode -- Linked List Cycle II
- JAVA去掉一个字符串的前后空格
- php eval使用
- 单片机 MSP430 模拟IIC编程(1)
- Android Intent 用法全面总结
- DBUtil的使用
- matlab 图像处理
- 响应式布局
- 内存对齐